<?php

namespace App\Http\Model;

use App\Http\Model\RoomBackgroundPicture\BackgroundPictureManagement;
use App\Http\Services\Meeting\MeetingServices;
use App\Lib\Search;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Room extends Base
{
    // 默认房间表 或房间推荐表:room_reco 或房间推荐热度系数表:room_recommend 或房间举报表:room_report
    public $table = 'room';

    // 房间功能开关
    public $tableRoomSwitch = 'room_switch';

    protected $roleTable = 'room_role';
    protected $roomAdmin = 'room_admin';
    protected $roomDynamicLogTable = 'room_dynamic_log';
    protected $roomDynamicTable = 'room_dynamic';
    protected $roomLivePlanTable = 'room_live_plan';
    protected $roomLiveSearchRecords = 'room_live_search_records';
    protected $roomLivePlanActive = 'room_live_plan_active';
    protected $roomMicroLogTable = 'room_micro_log';
    protected $room_special_table = 'room_special_config';//房间特殊配置
    protected $room_open_log_table = 'room_open_log';//房间-开启记录
    protected $room_user_msg_table = 'room_user_msg';//房间-用户聊天条数记录
    protected $room_top_table = 'room_top';//房间-置顶配置
    protected $roomFinanceUserTable = 'room_finance_user';//房间绑定结算账户
    protected $roomWelcomeWordTable = 'room_welcome_word';//房间-欢迎语
    protected $visitHistory = 'user_visit_history';//拜访记录表
    protected $roomPaipaiLogTable = 'room_paipai_log';//房间-拍拍房记录

    private $redis_shot_off = 'ROOM:SHOTOFF:'; // room:shotoff:{room_id}-{user_id}
    public $timestamps = false;
    private $redis_room_uid_index = "ROOM:UID:INDEX";
    private $redis_room_uid_lianghao = "ROOM:UID:LIANGHAO";
    private $sql_room_fields = ["room.room_id as room_id", "room.room_uid as room_uid", "room.name as name", "room.notice as notice",
        "room.image as image", "room.room_type as room_type",
        "room.action_type as action_type", "room.room_tag as room_tag", "room.user_id as user_id",
        "room.create_timestamp as create_timestamp", "room_type.type_id as type_id", "room_type.type_name as type_name",
        "room_type.img_home_url as img_home_url", "room_type.img_room_url as img_room_url", "room_type.img_roomedit_url as img_roomedit_url",
        "room.background_pic as background_pic", "room.room_tag as room_tag",
        "room.certified as certified",
        "room.desc as desc",
        "room.level as level",
        "room_level.icon as level_icon",
        "room.union_level as union_level",
        "room.room_tag_id as room_tag_id",
        "room.business_type as business_type",
        "room.room_liang_type as room_liang_type",
        "room_union_level.icon as union_level_icon",
        "room.heart as heart",
        "room.business_type as business_type",
        "room.room_liang_type as liang",
        "room_tag.id as tag_id",
        "room_tag.tag_name as tag_name",
        "room_tag.tag_color as tag_color",
        "room_tag.tag_color as tag_color",
        "room.tally as tally",
        "room.melee as melee",
        "room.turntable as turntable",
        "room.pk as pk",
        "room.spanpk as spanpk",
        "room.three_space as three_space",
        "room_type.model_str as model_str",
        "room.game_area as game_area",
        "room.game_level as game_level",
        "room_type.app_url as app_url",
        "room_type.default_background_pic as default_background_pic",
        "room.fleet_king as fleet_king",
        "room.fleet_peace as fleet_peace",
        "room.fleet_mult as fleet_mult",
        "room.vote as vote",
        "room.room_mode as room_mode",
        "room.is_hide",
    ];

    private $redis_cache_room_list = "ROOM:RANK:LIST:"; //CACHE:ROOM:LIST:{ROOM_TYPE}:{time()/1800} //房间列表 有序集合
    private $redis_cache_room_listrooms = "ROOM:RANK:LISTROOMS:";//CACHE:ROOM:LISTROOMS:{time()/1800} //标记房间是否加入到列表中 hash
    private $redis_cache_room_list_lasttag = "ROOM:RANK:LIST:LASTTAG"; //每个分类最后的时间tag hash

    private $redis_room = "ROOM:"; // ROOM:{room_id}
    private $redis_room_wait = "ROOM:WAIT";
    private $redis_room_opened = "ROOM:OPENED"; //已经开启的房间列表
    protected $primaryKey = 'room_id';

    private $redis_room_cache = 'CACHE:ROOM:';
    private $redis_room_recommend_cache = 'CACHE:ROOM:RECOMMEND';
    private $redisKeyRoomNameUpdateLimit = 'CACHE:ROOM:NAME:LIMIT:';
    private $redisKeyRoomUidGeneratedDB = "ROOM:UID:GENERATED:DB";
    private $redisRoomActionTypeLimitKey = "ROOM:ACTION:TYPE:LIMIT:";

    private $redisRoomFast = "CACHE:ROOM:FAST";
    private $roomTypeTable = 'room_type';
    private $roomTypePrimaryKey = 'type_id';
    // 统计房间进入新人人数
    private $roomJoinSizeNew = "ROOM:JOIN:SIZE:NEW:%d:%s:%d"; // roomId,20200202,userId
    // 统计房房间进入人数
    private $roomJoinSize = "ROOM:JOIN:SIZE:%d:%s:%d"; // roomId,20200202,userId

    private $roomOpenTimeTable = 'room_open_time';
    public $roomOpenTimes = 5*60; //5分钟统计一次

    protected $redis_room_reco_recommend = 'ROOM:RECO:RECOMMEND'; //热门配置推荐位
    protected $redis_room_reco2_recommend = 'ROOM:RECO2:RECOMMEND'; //房间推荐配置
    protected $table_recommend_label = 'room_recommend_label';
    protected $table_chat_private_log = 'room_chat_private_log';
    protected $table_join_log = 'room_join_log';
    protected $adapt_size ;
    protected $redis_dynamic_cover = 'ROOM:DYNAMIC:COVER:'; //动态封面
    protected $redis_room_label = 'ROOM:LABEL';

    protected $roleInviteTable = 'room_role_invite';
    CONST DEFAULT_ROOM_NAME = '聊天室';
    private $redis_room_god_hao_key = 'ROOM:GOD_HAO';
    private $redis_log_out_key = 'RONGCLOUD:LOGOUT';
    private $redis_man_log_out_key = 'RONGCLOUD:LOGOUT:MAN';
    private $redis_women_log_out_key = 'RONGCLOUD:LOGOUT:WOMAN';

    private $redis_room_type_list_key = 'ROOM:TYPE:LIST:';
    protected $redis_room_cover_special = 'ROOM:COVER:SPECIAL';//房间活动特殊封面
    protected $loveRankOpenStatusKey = 'ROOM:LOVE:RANK:OPEN';//set ROOM:LOVE:RANK:OPEN 开启房间真爱榜的房间集合

    //已开启房间信息
    protected $roomOpenListKey = 'ROOM:OPENLIST';

    //房间置顶配置
    protected $roomTopKey = 'ROOM:TOPLIST';

    //房间欢迎语缓存
    protected $roomWelcomeWordKey = 'ROOM:WELCOMEWORD:';//string 'ROOM:WELCOMEWORD:{roomId} => {string}

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
        $adapters = explode(',',Redis::HGET('IMAGE:ADAPT' ,'room'));
        $this->adapt_size = !empty($adapters) && count($adapters)>1 ? $adapters[1] : 480;
    }

    /**
     * 取出房间ID池中已生成的房间UID
     * @return int
     */
    public function generatedRoomUid(){
        return Redis::LPOP($this->redisKeyRoomUidGeneratedDB);
    }

    /**
     * 创建房间
     */
    public function create_room($data){
        $roomUid = $data['user_uid'] ?? ($data['room_uid'] ?? 0);
        if(empty($roomUid)){
            return false;
        }

        $businessType = $data['business_type'] ?? 0;//商业类型（0=小屋，1=CBD）

	$image = $this->randOneSmallRoomImage();

	$background_pic = '';
        if(!empty($data['room_type']) && $data['room_type']==46) {
            $background_pic = '/rank/paipai/background.png';
        }

        return DB::table($this->table)->insertGetId([
            'user_id'=> $data['user_id'],
            'room_uid'=> $roomUid,
            'name'=> $data['name'] ?? '',
            'notice'=> '',
            'image'=> $image,
            'background_pic'=> $background_pic,
            'room_type'=> $data['room_type'] ?? 0,
            'desc'=> '',
            'action_type'=>0,
            'room_mode'=>1,
            'create_timestamp' => time(),
            'business_type' => $businessType,
        ]);
    }

    /**
     * 随机一个小屋封面图
     *
     * Created at 2021/10/28 12:41
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @return string
     */
    private function randOneSmallRoomImage(): string
    {
        $images = ['/icon/xiaowu1.png', '/icon/xiaowu2.png', '/icon/xiaowu3.png', '/icon/xiaowu4.png'];
        return $images[rand(0, count($images) - 1)];
    }

    /**
     * 关键字搜索
     * */
    public function keywordsSearch($keywords,$businessType,$page,$limit){
        $keywords = filterEmoji($keywords);

        $search = new Search();
        $result = $search->searchRoom($keywords, $businessType, $page, $limit);

        return $this->checkPageData($page, $limit, 0, $result);
    }

    /**
     * 设置首页推荐
     * @param $rooms
     */
    public function set_rank($rooms){
        $time_tag =  intval(floor(time()/180));
        //$arr = Redis::KEYS($this->redis_cache_room_list . '*');
        //$arr1 = Redis::KEYS($this->redis_cache_room_listrooms . '*');
        $arr_update_id = [];
        foreach ($rooms as $k => $v){
            $type_key = $this->redis_cache_room_list . $v['room_type']['id'] . ':' . $time_tag;
            $all_key = $this->redis_cache_room_list . '-1' . ':' . $time_tag;
            $type_rooms_key = $this->redis_cache_room_listrooms .  $v['room_type']['id'] . ':' . $time_tag;
            $all_rooms_key = $this->redis_cache_room_listrooms . '-1' . ':' . $time_tag;
            if (empty(Redis::HGET($type_rooms_key, $v['room_id']))){
                Redis::HSET($type_rooms_key, $v['room_id'], json_encode($v));
                Redis::ZADD($type_key, intval($v['user_count'])*10000000000 + intval($v['into_time']), json_encode($v));
                $arr_update_id[strval($v['room_type']['id'])] = $time_tag;
                //Redis::HSET($this->redis_cache_room_list_lasttag, strval($v['room_type']['id']), $time_tag);
            }
            if (empty(Redis::HGET($all_rooms_key, $v['room_id']))){
                Redis::HSET($all_rooms_key, $v['room_id'], json_encode($v));
                Redis::ZADD($all_key, $v['rank_value'], json_encode($v));
                $arr_update_id['-1'] = $time_tag;
                //Redis::HSET($this->redis_cache_room_list_lasttag, '-1', $time_tag);
            }
        }
        $old_lasttag = Redis::HGETALL($this->redis_cache_room_list_lasttag);

        // 新设置的
        foreach ($arr_update_id as $k => $v){
            Redis::HSET($this->redis_cache_room_list_lasttag, $k, $time_tag);
            if (isset($old_lasttag[$k]) && $old_lasttag[$k] != $time_tag){
                Redis::DEL($this->redis_cache_room_list . $k . ':' . $old_lasttag[$k]);
                Redis::DEL($this->redis_cache_room_listrooms . $k . ':' . $old_lasttag[$k]);
            }
        }

        $lasttag = Redis::HGETALL($this->redis_cache_room_list_lasttag);
        // 丢弃掉的
        foreach ($lasttag as $k => $v){
            if ($v != $time_tag) {
                Redis::HDEL($this->redis_cache_room_list_lasttag, $k);
                Redis::DEL($this->redis_cache_room_list . $k . ':' . $v);
                Redis::DEL($this->redis_cache_room_listrooms . $k . ':' . $v);
            }
        }

        /*
        foreach ($arr as $v){
            if (strpos($v, strval($time_tag)) == false){
                Redis::DEL($v);
            }
        }
        foreach ($arr1 as $v){
            if (strpos($v, strval($time_tag)) == false){
                Redis::DEL($v);
            }
        }
        */

    }

    /**
     * 添加一条数据到推荐
     * @param $room
     */
    public function set_rank_one($room){
        $time_tag = Redis::HGET($this->redis_cache_room_list_lasttag, $room['room_type']['id']);
        if ($time_tag === null){
            $time_tag = intval(floor(time()/180));
        }
        $type_key = $this->redis_cache_room_list . $room['room_type']['id'] . ':' . $time_tag;
        $type_rooms_key = $this->redis_cache_room_listrooms .  $room['room_type']['id'] . ':' . $time_tag;
        if (empty(Redis::HGET($type_rooms_key, $room['room_id']))){
            Redis::HSET($type_rooms_key, $room['room_id'], json_encode($room));
            Redis::ZADD($type_key, intval($room['user_count'])*10000000000 + intval($room['into_time']), json_encode($room));
            Redis::HSET($this->redis_cache_room_list_lasttag, $room['room_type']['id'], $time_tag);
        }
    }

    /**
     * 获取首页推荐
     * @param $room_type_id
     * @param $offset
     * @param $limit
     * @return array|null
     */
    public function get_rank($room_type_id, $offset, $limit){
        $time_tag = Redis::HGET($this->redis_cache_room_list_lasttag, $room_type_id);
        if (empty($time_tag)){
            return [];
        }
        $key = $type_rooms_key = $this->redis_cache_room_list .  $room_type_id . ':' . $time_tag;
        $data = Redis::ZREVRANGE($key, $offset, $offset + $limit-1, 'WITHSCORES');
        $ret = [];
        foreach ($data as $k => $v){
            $res = json_decode($k, true);
            $res['room_tag'] = $res['room_tag'] ? getPicDomain().$res['room_tag'] : '';
            $ret[] = $res;
        }
        return $ret;
    }

    /**
     * 获取首页推荐个数
     * @param $room_type_id
     * @return null
     */
    public function get_rank_count($room_type_id){
        $time_tag = Redis::HGET($this->redis_cache_room_list_lasttag, $room_type_id);
        if (empty($time_tag)){
            return 0;
        }
        $key = $type_rooms_key = $this->redis_cache_room_list .  $room_type_id . ':' . $time_tag;
        return Redis::ZCARD($key);
    }




    /**
     * 获取房间列表
     * @param $room_type_id
     * @return array
     */

    public function get_rooms($room_type_id){
        if ($room_type_id == -1){
            $rooms = DB::table('room')
                ->leftJoin("room_type", "room.room_type", "=", "room_type.type_id")
                ->leftJoin("room_level", "room.level", "=", "room_level.id")
                ->leftJoin("room_union_level", "room.union_level", "=", "room_union_level.id")
                ->leftJoin("room_tag", "room.room_tag_id", "=", "room_tag.id")
                ->get($this->sql_room_fields);
        }else{
            $rooms = DB::table('room')
                ->leftJoin("room_type", "room.room_type", "=", "room_type.type_id")
                ->leftJoin("room_level", "room.level", "=", "room_level.id")
                ->leftJoin("room_union_level", "room.union_level", "=", "room_union_level.id")
                ->leftJoin("room_tag", "room.room_tag_id", "=", "room_tag.id")
                ->where('room.room_type', '=', $room_type_id)
                ->get($this->sql_room_fields);
        }

        $result = self::objToArray($rooms);
        for ($i = 0; $i < count($result); $i++){
            $result[$i]["room_type"] = [];
            if(!$result[$i]["name"]) $result[$i]["name"] = self::DEFAULT_ROOM_NAME;
            $result[$i]["room_type"]["id"] = $result[$i]["type_id"];
            $result[$i]["room_type"]["type_name"] = $result[$i]["type_name"];
            $result[$i]["room_type"]["img_home_url"] = build_image($result[$i]["img_home_url"]);
            $result[$i]["room_type"]["img_room_url"] = build_image($result[$i]["img_room_url"]);
            $result[$i]["room_type"]["img_roomedit_url"] = build_image($result[$i]["img_roomedit_url"]);

            //$result[$i]["room_tag"] = [];
            //$result[$i]["room_tag"]["id"] = $result[$i]["tag_id"];
            //$result[$i]["room_tag"]["name"] = $result[$i]["tag_name"];
            //$result[$i]["room_tag"]["color"] = $result[$i]["tag_color"];

            $result[$i]["background_pic"] = build_image($result[$i]["background_pic"]);
            if (!empty($result[$i]["default_background_pic"])){
                $result[$i]["type_background_pic"] = build_image($result[$i]["default_background_pic"]);
            }

            if(!$result[$i]['image']) $result[$i]['image'] = '/room/image_default.png';
            //图片尺寸适配
            $result[$i]['adapt_image'] = build_adapt_images($result[$i]["image"] ,$this->adapt_size);
            $result[$i]["image"] = build_image_small($result[$i]["image"]);
            $result[$i]["level_icon"] = build_image($result[$i]["level_icon"]);
            $result[$i]["union_level_icon"] = build_image($result[$i]["union_level_icon"]);
            $result[$i]["game_area"] = $result[$i]["game_area"] ? explode(",", $result[$i]["game_area"]) : [];
            $result[$i]["game_level"] = $result[$i]["game_level"] ? explode(",", $result[$i]["game_level"]) : [];
            $result[$i]["game_desc"] = (!empty($result[$i]["game_area"]) && !empty($result[$i]["game_level"])) ? $result[$i]["game_area"][0] . "|" . implode("/", $result[$i]["game_level"]) : "";

//            unset($result[$i]["type_id"]);
            unset($result[$i]["type_name"]);
            unset($result[$i]["img_home_url"]);
            unset($result[$i]["img_room_url"]);
            unset($result[$i]["img_roomedit_url"]);
        }
        return $result;
    }


    public function get_recommends(){
        $data = DB::table('room_recommend')->get();
        $result = self::objToArray($data);
        $recommends = [];
        for ($i = 0; $i < count($result); $i++){
            $recommends[$result[$i]['room_id']] = $result[$i]['coefficient'];
        }
        return $recommends;
    }
    public function get_recommend_rand($room_id){
        $key = $this->redis_room_recommend_cache.':RAND';
        $data = Redis::HGET($key, $room_id);
        if (!empty($data)){
            return intval($data);
        }
        $num = rand(50000,59999);
        Redis::HSET($key, $room_id, $num);
        if (Redis::TTL($key) == -1){
            Redis::EXPIRE($key, 1800);
        }
        return $num;
    }
    public function get_recommend($room_id){
        $data = Redis::HGET($this->redis_room_recommend_cache, $room_id);
        if (!empty($data)){
            return intval($data);
        }
        $data = DB::table('room_recommend')
            ->where('room_id', '=', $room_id)
            ->first();
        if (empty($data)){
            return 0;
        }
        $result = self::objToArray($data);
        Redis::HSET($this->redis_room_recommend_cache, $room_id, $result['coefficient']);
        if (Redis::TTL($this->redis_room_recommend_cache) == -1){
            Redis::EXPIRE($this->redis_room_recommend_cache, 1800);
        }
        return intval($result['coefficient']);

    }

    //新增或更新预置厅分数
    public function updateRoomCoefficient($roomId, $coefficient){
        $info = DB::table('room_recommend')->where('room_id', $roomId)->first();
        if(empty($info)) {
            DB::table('room_recommend')->insert(['room_id'=>$roomId, 'coefficient'=>$coefficient]);
        }else{
            DB::table('room_recommend')->where('room_id', $roomId)->update(['coefficient'=>$coefficient]);
        }
        Redis::HDEL($this->redis_room_recommend_cache, $roomId);
    }


    /**
     * 获取房间列表 limit
     * @param $room_type_id
     * @param $offset
     * @param $limit
     * @return mixed
     */
    public function get_rooms_limit($room_type_id, $offset, $limit){
        $rooms = DB::table('room')
            ->leftJoin("room_type", "room.room_type", "=", "room_type.type_id")
            ->leftJoin("room_level", "room.level", "=", "room_level.id")
            ->leftJoin("room_union_level", "room.union_level", "=", "room_union_level.id")
            ->leftJoin("room_tag", "room.room_tag_id", "=", "room_tag.id")
            ->where('room.room_type', '=', $room_type_id)
            ->offset($offset)
            ->limit($limit)
            ->get($this->sql_room_fields);
        $result = self::objToArray($rooms);
        for ($i = 0; $i < count($result); $i++){
            $result[$i]["room_type"] = [];
            if(!$result[$i]["name"]) $result[$i]["name"] = self::DEFAULT_ROOM_NAME;
            $result[$i]["room_type"]["id"] = $result[$i]["type_id"];
            $result[$i]["room_type"]["type_name"] = $result[$i]["type_name"];
            $result[$i]["room_type"]["img_home_url"] = build_image($result[$i]["img_home_url"]);
            $result[$i]["room_type"]["img_room_url"] = build_image($result[$i]["img_room_url"]);
            $result[$i]["room_type"]["img_roomedit_url"] = build_image($result[$i]["img_roomedit_url"]);

//            $result[$i]["room_tag"] = [];
//            $result[$i]["room_tag"]["id"] = $result[$i]["tag_id"];
//            $result[$i]["room_tag"]["name"] = $result[$i]["tag_name"];
//            $result[$i]["room_tag"]["color"] = $result[$i]["tag_color"];
            if(!$result[$i]['image']) $result[$i]['image'] = '/room/image_default.png';
            //图片尺寸适配
            $result[$i]['adapt_image'] = build_adapt_images($result[$i]["image"] ,$this->adapt_size);

            $result[$i]["background_pic"] = build_image($result[$i]["background_pic"]);
            $result[$i]["image"] = build_image($result[$i]["image"]);
            $result[$i]["level_icon"] = build_image($result[$i]["level_icon"]);
            $result[$i]["union_level_icon"] = build_image($result[$i]["union_level_icon"]);
            $result[$i]["game_area"] = $result[$i]["game_area"] ? explode(",", $result[$i]["game_area"]) : [];
            $result[$i]["game_level"] = $result[$i]["game_level"] ? explode(",", $result[$i]["game_level"]) : [];
            $result[$i]["game_desc"] = (!empty($result[$i]["game_area"]) && !empty($result[$i]["game_level"])) ? $result[$i]["game_area"][0] . "|" . implode("/", $result[$i]["game_level"]) : "";

//            unset($result[$i]["type_id"]);
            unset($result[$i]["type_name"]);
            unset($result[$i]["img_home_url"]);
            unset($result[$i]["img_room_url"]);
            unset($result[$i]["img_roomedit_url"]);
        }
        return $result;
    }


    /**
     * 获取房间列表总数量
     * @param $room_type_id
     * @return int
     */
    public function get_rooms_count($room_type_id){
        $rooms_count = DB::table('room')
            ->where('room_type', '=', $room_type_id)
            ->count();
        return $rooms_count;
    }


    /**
     * 获取最新列表
     * @return mixed
     */
    public function get_new_rooms(){
        $rooms = DB::table('room')
            ->leftJoin("room_type", "room.room_type", "=", "room_type.type_id")
            ->leftJoin("room_level", "room.level", "=", "room_level.id")
            ->leftJoin("room_union_level", "room.union_level", "=", "room_union_level.id")
            ->leftJoin("room_tag", "room.room_tag_id", "=", "room_tag.id")
            ->orderBy("create_timestamp", "desc")
            ->get($this->sql_room_fields);
        $result = self::objToArray($rooms);
        for ($i = 0; $i < count($result); $i++){
            $result[$i]["room_type"] = [];
            if(!$result[$i]["name"]) $result[$i]["name"] = self::DEFAULT_ROOM_NAME;
            $result[$i]["room_type"]["id"] = $result[$i]["type_id"];
            $result[$i]["room_type"]["type_name"] = $result[$i]["type_name"];
            $result[$i]["room_type"]["img_home_url"] = build_image($result[$i]["img_home_url"]);
            $result[$i]["room_type"]["img_room_url"] = build_image($result[$i]["img_room_url"]);
            $result[$i]["room_type"]["img_roomedit_url"] = build_image($result[$i]["img_roomedit_url"]);
//
//            $result[$i]["room_tag"] = [];
//            $result[$i]["room_tag"]["id"] = $result[$i]["tag_id"];
//            $result[$i]["room_tag"]["name"] = $result[$i]["tag_name"];
//            $result[$i]["room_tag"]["color"] = $result[$i]["tag_color"];

            if(!$result[$i]['image']) $result[$i]['image'] = '/room/image_default.png';
            //图片尺寸适配
            $result[$i]['adapt_image'] = build_adapt_images($result[$i]["image"] ,$this->adapt_size);

            $result[$i]["background_pic"] = build_image($result[$i]["background_pic"]);
            $result[$i]["image"] = build_image($result[$i]["image"]);
            $result[$i]["level_icon"] = build_image($result[$i]["level_icon"]);
            $result[$i]["union_level_icon"] = build_image($result[$i]["union_level_icon"]);
            $result[$i]["game_area"] = $result[$i]["game_area"] ? explode(",", $result[$i]["game_area"]) : [];
            $result[$i]["game_level"] = $result[$i]["game_level"] ? explode(",", $result[$i]["game_level"]) : [];
            $result[$i]["game_desc"] = (!empty($result[$i]["game_area"]) && !empty($result[$i]["game_level"])) ? $result[$i]["game_area"][0] . "|" . implode("/", $result[$i]["game_level"]) : "";

//            unset($result[$i]["type_id"]);
            unset($result[$i]["type_name"]);
            unset($result[$i]["img_home_url"]);
            unset($result[$i]["img_room_url"]);
            unset($result[$i]["img_roomedit_url"]);
        }
        return $result;
    }

    /**
     * 获取最新列表 limit
     * @param $offset
     * @param $limit
     * @return mixed
     */
    public function get_new_rooms_limit($offset, $limit){
        $rooms = DB::table('room')
            ->leftJoin("room_type", "room.room_type", "=", "room_type.type_id")
            ->leftJoin("room_level", "room.level", "=", "room_level.id")
            ->leftJoin("room_union_level", "room.union_level", "=", "room_union_level.id")
            ->leftJoin("room_tag", "room.room_tag_id", "=", "room_tag.id")
            ->orderBy("create_timestamp", "desc")
            ->offset($offset)
            ->limit($limit)
            ->get($this->sql_room_fields);
        $result = self::objToArray($rooms);
        for ($i = 0; $i < count($result); $i++){
            $result[$i]["room_type"] = [];
            if(!$result[$i]["name"]) $result[$i]["name"] = self::DEFAULT_ROOM_NAME;
            $result[$i]["room_type"]["id"] = $result[$i]["type_id"];
            $result[$i]["room_type"]["type_name"] = $result[$i]["type_name"];
            $result[$i]["room_type"]["img_home_url"] = build_image($result[$i]["img_home_url"]);
            $result[$i]["room_type"]["img_room_url"] = build_image($result[$i]["img_room_url"]);
            $result[$i]["room_type"]["img_roomedit_url"] = build_image($result[$i]["img_roomedit_url"]);


//            $result[$i]["room_tag"] = [];
//            $result[$i]["room_tag"]["id"] = $result[$i]["tag_id"];
//            $result[$i]["room_tag"]["name"] = $result[$i]["tag_name"];
//            $result[$i]["room_tag"]["color"] = $result[$i]["tag_color"];

            if(!$result[$i]['image']) $result[$i]['image'] = '/room/image_default.png';
            //图片尺寸适配
            $result[$i]['adapt_image'] = build_adapt_images($result[$i]["image"] ,$this->adapt_size);

            $result[$i]["background_pic"] = build_image($result[$i]["background_pic"]);
            $result[$i]["image"] = build_image($result[$i]["image"]);
            $result[$i]["level_icon"] = build_image($result[$i]["level_icon"]);
            $result[$i]["union_level_icon"] = build_image($result[$i]["union_level_icon"]);
            $result[$i]["game_area"] = $result[$i]["game_area"] ? explode(",", $result[$i]["game_area"]) : [];
            $result[$i]["game_level"] = $result[$i]["game_level"] ? explode(",", $result[$i]["game_level"]) : [];
            $result[$i]["game_desc"] = (!empty($result[$i]["game_area"]) && !empty($result[$i]["game_level"])) ? $result[$i]["game_area"][0] . "|" . implode("/", $result[$i]["game_level"]) : "";

//            unset($result[$i]["type_id"]);
            unset($result[$i]["type_name"]);
            unset($result[$i]["img_home_url"]);
            unset($result[$i]["img_room_url"]);
            unset($result[$i]["img_roomedit_url"]);
        }
        return $result;
    }


    /**
     * 获取最新列表数量
     */
    public function get_new_rooms_count(){
        $rooms_count = DB::table('room')->count();
        return $rooms_count;
    }


    /**
     * 获取房间列表
     * @param $list_room_id room_id数组
     * @return array
     */
    public function get_rooms_by_ids($list_room_id){
        if (empty($list_room_id)){
            return [];
        }

        $data = Redis::MGET(array_map(function ($roomId){
            return $this->redis_room_cache. $roomId;
        }, $list_room_id));
        $ret_data = [];
        foreach ($data as $k => $v){
            if (!empty($v)){
                $ret_data[$list_room_id[$k]] = json_decode($v, true);
                unset($list_room_id[$k]);
            }

        }
        if (empty($list_room_id)){
            return array_values($ret_data);
        }
        $rooms = DB::table('room')
            ->leftJoin("room_type", "room.room_type", "=", "room_type.type_id")
            ->leftJoin("room_level", "room.level", "=", "room_level.id")
            ->leftJoin("room_union_level", "room.union_level", "=", "room_union_level.id")
            ->leftJoin("room_tag", "room.room_tag_id", "=", "room_tag.id")
            ->whereIn("room.room_id", $list_room_id)
            ->get($this->sql_room_fields);
        $result = self::objToArray($rooms);
        $search = new Search();
        for ($i = 0; $i < count($result); $i++){
            $result[$i]["room_type"] = [];
            if(!$result[$i]["name"]) $result[$i]["name"] = self::DEFAULT_ROOM_NAME;
            $result[$i]["room_type"]["id"] = $result[$i]["type_id"];
            $result[$i]["room_type"]["type_name"] = $result[$i]["type_name"];
            $result[$i]["room_type"]["img_home_url"] = build_image($result[$i]["img_home_url"]);
            $result[$i]["room_type"]["img_room_url"] = build_image($result[$i]["img_room_url"]);
            $result[$i]["room_type"]["img_roomedit_url"] = build_image($result[$i]["img_roomedit_url"]);

            if(!$result[$i]['image']) $result[$i]['image'] = '/room/image_default.png';
            //图片尺寸适配
            $result[$i]['adapt_image'] = build_adapt_images($result[$i]["image"] ,$this->adapt_size);

            $result[$i]["background_pic"] = build_image($result[$i]["background_pic"]);
            $result[$i]["image"] = build_image($result[$i]["image"]);
            $result[$i]["level_icon"] = build_image($result[$i]["level_icon"]);
            $result[$i]["union_level_icon"] = build_image($result[$i]["union_level_icon"]);

            unset($result[$i]["type_name"]);
            unset($result[$i]["img_home_url"]);
            unset($result[$i]["img_room_url"]);
            unset($result[$i]["img_roomedit_url"]);

            $result[$i]["game_area"] = $result[$i]["game_area"] ? explode(",", $result[$i]["game_area"]) : [];
            $result[$i]["game_level"] = $result[$i]["game_level"] ? explode(",", $result[$i]["game_level"]) : [];
            $result[$i]["game_desc"] = (!empty($result[$i]["game_area"]) && !empty($result[$i]["game_level"])) ? $result[$i]["game_area"][0] . "|" . implode("/", $result[$i]["game_level"]) : "";
            $result[$i]['dynamic_cover'] = !empty(Redis::get($this->redis_dynamic_cover.$result[$i]['room_id'])) ? Redis::get($this->redis_dynamic_cover.$result[$i]['room_id']) : '';
            $result[$i]['recommend_label'] = !empty(Redis::hget($this->redis_room_label ,$result[$i]['room_id'])) ? Redis::hget($this->redis_room_label ,$result[$i]['room_id']) : '';
            $ret_data[$result[$i]['room_id']] = $result[$i];
            $search->indexRoom($result[$i]);
            Redis::SET($this->redis_room_cache . $result[$i]['room_id'], json_encode($result[$i]), 'EX', 3600);
        }
        return array_values($ret_data);
    }

    /**
     * 根据房间ID获取房间信息
     *
     * @param int $roomId
     * @return array
     */
    public function getRoomById($roomId)
    {
        $result = DB::table($this->table)
            ->select(['room_id', 'name', 'business_type','room_uid', 'user_id'])
            ->where('room_id', '=', $roomId)
            ->first();

        return self::objToArray($result);
    }

    /**
     * 获取房间基本信息
     * @param $uRoomIds array
     * @return mixed
     */
    public function getRoomIdByUids($uRoomIds)
    {
        $result = DB::table($this->table)
            ->whereIn('room_uid', $uRoomIds)
            ->pluck('room_id');

        return self::objToArray($result);
    }

    /**
     * 获得房间信息
     * @param $room_id
     * @return mixed|null
     */
    public function get_room($room_id){
        $data = Redis::GET($this->redis_room_cache . $room_id);
        if (!empty($data)){
            return json_decode($data, true);
        }
        $room = DB::table($this->table)
            ->leftJoin("room_type", "room.room_type", "=", "room_type.type_id")
            ->leftJoin("room_level", "room.level", "=", "room_level.id")
            ->leftJoin("room_union_level", "room.union_level", "=", "room_union_level.id")
            ->leftJoin("room_tag", "room.room_tag_id", "=", "room_tag.id")
            ->where('room.room_id', '=', $room_id)
            ->first($this->sql_room_fields);
        if (empty($room)){
            return null;
        }
        $result = self::objToArray($room);
        $result["room_type"] = [];
        if(!$result["name"]) $result["name"] = self::DEFAULT_ROOM_NAME;
        $result["room_type"]["id"] = $result["type_id"];
        $result["room_type"]["type_name"] = $result["type_name"];
        $result["room_type"]["img_home_url"] = build_image($result["img_home_url"]);
        $result["room_type"]["img_room_url"] = build_image($result["img_room_url"]);
        $result["room_type"]["img_roomedit_url"] = build_image($result["img_roomedit_url"]);

        $result["game_area"] = $result["game_area"] ? explode(",", $result["game_area"]) : [];
        $result["game_level"] = $result["game_level"] ? explode(",", $result["game_level"]) : [];
        $result["game_desc"] = (!empty($result["game_area"]) && !empty($result["game_level"])) ? $result["game_area"][0] . "|" . implode("/", $result["game_level"]) : "";

        $result["background_pic"] = build_image($result["background_pic"]);

        if (!empty($result["default_background_pic"])){
            $result["type_background_pic"] = build_image($result["default_background_pic"]);
        }

        if(!$result['image']) $result['image'] = '/room/image_default.png';
        //图片尺寸适配
        $result['adapt_image'] = build_adapt_images($result["image"] ,$this->adapt_size);
        $result["image"] = build_image($result["image"]);

        $result["level_icon"] = build_image($result["level_icon"]);
        $result["union_level_icon"] = build_image($result["union_level_icon"]);
        $result['dynamic_cover'] = !empty(Redis::get($this->redis_dynamic_cover.$result['room_id'])) ? Redis::get($this->redis_dynamic_cover.$result['room_id']) : '';
        $result['recommend_label'] = !empty(Redis::hget($this->redis_room_label ,$result['room_id'])) ? Redis::hget($this->redis_room_label ,$result['room_id']) : '';

        unset($result["type_name"]);
        unset($result["img_home_url"]);
        unset($result["img_room_url"]);
        unset($result["img_roomedit_url"]);
        $search = new Search();
        $search->indexRoom($result);
        Redis::SET($this->redis_room_cache . $room_id, json_encode($result), 'EX', 3600);
        return $result;
    }





    public function get_room_by_userid($user_id){
        $room = DB::table($this->table)
            ->leftJoin("room_type", "room.room_type", "=", "room_type.type_id")
            ->leftJoin("room_level", "room.level", "=", "room_level.id")
            ->leftJoin("room_union_level", "room.union_level", "=", "room_union_level.id")
            ->leftJoin("room_tag", "room.room_tag_id", "=", "room_tag.id")
            ->where('user_id', '=', $user_id)
            ->where('business_type', '=', 0)
            ->first($this->sql_room_fields);
        if (empty($room)){
            return null;
        }
        $result = self::objToArray($room);
        $result["room_type"] = [];
        if(!$result["name"]) $result["name"] = self::DEFAULT_ROOM_NAME;
        $result["room_type"]["id"] = $result["type_id"];
        $result["room_type"]["type_name"] = $result["type_name"];
        $result["room_type"]["img_home_url"] = build_image($result["img_home_url"]);
        $result["room_type"]["img_room_url"] = build_image($result["img_room_url"]);
        $result["room_type"]["img_roomedit_url"] = build_image($result["img_roomedit_url"]);

//        $result["room_tag"] = [];
//        $result["room_tag"]["id"] = $result["tag_id"];
//        $result["room_tag"]["name"] = $result["tag_name"];
//        $result["room_tag"]["color"] = $result["tag_color"];

        if(!$result['image']) $result['image'] = '/room/image_default.png';
        //图片尺寸适配
        $result['adapt_image'] = build_adapt_images($result["image"] ,$this->adapt_size);

        $result["background_pic"] = build_image($result["background_pic"]);
        $result["image"] = build_image($result["image"]);
        $result["level_icon"] = build_image($result["level_icon"]);
        $result["union_level_icon"] = build_image($result["union_level_icon"]);

        unset($result["type_id"]);
        unset($result["type_name"]);
        unset($result["img_home_url"]);
        unset($result["img_room_url"]);
        unset($result["img_roomedit_url"]);
        return $result;
    }


    /****************************************权限**********************************************************************/

    /**
     * 创建权限
     * @param $room_id
     * @param $user_id
     * @param $role_type
     * @return bool
     */
    public function add_role($room_id, $user_id, $role_type){
        $data = [
            'room_id'=>$room_id,
            'user_id'=>$user_id,
            'role_type'=>$role_type,
            'create_timestamp' => time()
        ];
        $result = DB::table($this->roleTable)->insert($data);
        return $result;
    }

    /**
     * 删除权限 房主不能删除
     * @param $room_id
     * @param $user_id
     * @return bool
     */
    public function del_role($room_id, $user_id){
        $result = DB::table($this->roleTable)
            ->where("room_id", "=", $room_id)
            ->where("user_id", "=", $user_id)
            ->where("role_type", "<>", 2) //忽略房主
            ->delete();
        return $result;
    }


    /**
     * 删除所有管理
     * @param $room_id
     * @param $user_id
     * @return bool
     */
    public function del_all_role($room_id){
        $result = DB::table($this->roleTable)
            ->where("room_id", "=", $room_id)
            ->where("role_type", "<>", 2) //忽略房主
            ->delete();
        return $result;
    }

    /**（公会添加）
     * 删除权限 房主不可删除  房主权限可删除
     * @param $room_id
     * @param $user_id
     * @return bool
     */
    public function del_role_join_room($room_id, $user_id){
        $result = DB::table($this->roleTable)
            ->where("room_role.room_id", "=", $room_id)
            ->where("room_role.user_id", "=", $user_id)
            ->leftJoin("room", "room.room_id", "=", "room_role.room_id")
            ->where("room.user_id", "!=", $user_id)
            ->delete();
        return $result;
    }

    /**
     * 获取权限列表
     * @param $room_id
     * @return array
     */
    public function get_roles($room_id){
        $roles = DB::table('room_role')
            ->where('room_role.room_id', $room_id)
            ->get(['room_role.user_id as user_id']);
        $result = self::objToArray($roles);
        return $result;
    }

    /**
     * 获取权限列表
     * @param $room_id
     * @return array
     */
    public function getRoles($room_id){
        $roles = DB::table('room_role')
            ->where('room_id', $room_id)
            ->get();
        $result = self::objToArray($roles);
        return $result;
    }


    /**
     * 获取权限列表 limit
     * @param $room_id
     * @param $offset
     * @param $limit
     * @return mixed
     */
    public function get_roles_limit($room_id, $offset, $limit){
        $roles = DB::table('room_role')
            ->where('room_role.room_id', $room_id)
            ->offset($offset)
            ->limit($limit)
            ->get(['room_role.user_id as user_id','room_role.role_type as role_type']);
        $result = self::objToArray($roles);
        return $result;
    }


    /**
     * 获取权限数量
     * @param $room_id
     * @return int
     */
    public function get_roles_count($room_id){
        $roles_count = DB::table('room_role')
            ->where('room_role.room_id', $room_id)
            ->count();
        return $roles_count;
    }

    /**
     * 获取房间各种权限人数
     * @param $room_id
     * @return array
     */
    public function get_roles_all_count($room_id){
        $roles_count = DB::table('room_role')
            ->where('room_role.room_id', $room_id)
            ->selectRaw('role_type, count(role_id) as count_role_id')
            ->groupBy('role_type')->get();
        return $this->objToArray($roles_count);
    }

    /**
     * 获取房间某个权限用户信息
     * @param $room_id
     * @param $role_type  0:普通用户 1：管理员 2：房主
     * @return array
     */
    public function get_roles_all_by_role_type($room_id,$role_type = 0){
        $where['room_id'] = $room_id;
        $where['role_type'] = $role_type;
        $roles_count = DB::table('room_role')
            ->where($where)
            ->leftJoin("user", "user.user_id", "=", "room_role.user_id")
            ->select('room_role.*','nickname','uuid','portrait')
            ->get();
        return $this->objToArray($roles_count);
    }


    /**
     * 获取当前用户房间权限
     * @param $room_id
     * @param $user_id
     * @return int 0:普通用户 1：管理员 2：房主
     */
    public function get_role($room_id, $user_id){
        $result = DB::table("room_role")
            ->where("room_id", $room_id)
            ->where("user_id", $user_id)
            ->first(['role_type']);
        if (empty($result)){
            return 0;
        }
        $result = self::objToArray($result);
        return $result['role_type'];
    }

    /**
     * 获取用户拥有权限的房间
     * @param $user_id
     * @return mixed
     */
    public function get_role_rooms($user_id){
        $fields = $this->sql_room_fields;
        $fields[] = 'room_role.role_type as role_type';
        $rooms = DB::table('room_role')
            ->leftJoin('room', "room_role.room_id", "=", "room.room_id")
            ->leftJoin("room_type", "room.room_type", "=", "room_type.type_id")
            ->leftJoin("room_level", "room.level", "=", "room_level.id")
            ->leftJoin("room_union_level", "room.union_level", "=", "room_union_level.id")
            ->leftJoin("room_tag", "room.room_tag_id", "=", "room_tag.id")
            ->where('room_role.user_id', '=', $user_id)
            ->orderBy('room.certified')
            ->orderBy('room_role.role_id')
            ->get($fields);
        $result = self::objToArray($rooms);
        for ($i = 0; $i < count($result); $i++){
            $result[$i]["room_type"] = [];
            if(!$result[$i]["name"]) $result[$i]["name"] = self::DEFAULT_ROOM_NAME;
            $result[$i]["room_type"]["id"] = $result[$i]["type_id"];
            $result[$i]["room_type"]["type_name"] = $result[$i]["type_name"];
            $result[$i]["room_type"]["img_home_url"] = build_image($result[$i]["img_home_url"]);
            $result[$i]["room_type"]["img_room_url"] = build_image($result[$i]["img_room_url"]);
            $result[$i]["room_type"]["img_roomedit_url"] = build_image($result[$i]["img_roomedit_url"]);
            $result[$i]["background_pic"] = build_image($result[$i]["background_pic"]);

            if(!$result[$i]['image']) $result[$i]['image'] = '/room/image_default.png';
            //图片尺寸适配
            $result[$i]['adapt_image'] = build_adapt_images($result[$i]["image"] ,$this->adapt_size);

            $result[$i]["image"] = build_image($result[$i]["image"]);
            $result[$i]["level_icon"] = build_image($result[$i]["level_icon"]);
            $result[$i]["union_level_icon"] = build_image($result[$i]["union_level_icon"]);
            $result[$i]["game_area"] = $result[$i]["game_area"] ? explode(",", $result[$i]["game_area"]) : [];
            $result[$i]["game_level"] = $result[$i]["game_level"] ? explode(",", $result[$i]["game_level"]) : [];
            $result[$i]["game_desc"] = (!empty($result[$i]["game_area"]) && !empty($result[$i]["game_level"])) ? $result[$i]["game_area"][0] . "|" . implode("/", $result[$i]["game_level"]) : "";

//            unset($result[$i]["type_id"]);
            unset($result[$i]["type_name"]);
            unset($result[$i]["img_home_url"]);
            unset($result[$i]["img_room_url"]);
            unset($result[$i]["img_roomedit_url"]);
        }
        return $result;
    }

    /**
     * 获取用户管理员房间个数
     * @param $user_id
     * @return int
     */
    public function get_role_room_count($user_id){
        $room_count = DB::table('room_role')
            ->where('user_id', '=', $user_id)
            ->count();
        return $room_count;
    }

    /**
     * 读取一个用户在每个房间的权限
     * @param $user_id int 用户id
     * @param $role_type int 权限 0:普通用户 1：管理员 2：房主
     * @param $room_id array 房间id列表
     * @return array
     */
    public function get_roles_by_room_ids(int $user_id, int $role_type = 0,array $room_ids = []){
        $roles = DB::table('room_role');
        if (count($room_ids) > 0) {
            $roles->whereIn('room_id', $room_ids);
        }

        if ($role_type > 0) {
            $roles->where('role_type', $role_type);
        }

        $lists = $roles->where('user_id', $user_id)
            ->get(['room_id', 'role_type']);
        $result = self::objToArray($lists);
        return $result;
    }

    /**获取用户的小屋room_id
     * @param $user_id
     * @return int
     */
    public function get_user_room_id($user_id){
        $room =  DB::table('room')->where(['user_id'=>$user_id ,'business_type'=>0])->first();
        return empty($room) ? [] : [$room->room_id];
    }

    /**判断是否为小屋
     * @param $room_id
     * @return int
     */
    public function get_room_business_type($room_id){
        $type =  DB::table('room')->where(['room_id'=>$room_id])->select('business_type')->first();
        return $type->business_type;
    }

    /**
     * 根据房间id获取管理员id
     */
    public function getAllAdminUserByRoomId($room_id){
        $allAdminids = DB::table('room_role')
                    ->where('room_id',$room_id)
                    ->where('role_type', 2)
                    ->get(['user_id']);
        $allAdminids = self::objToArray($allAdminids);
        return $allAdminids;
    }
    /******************************黑名单******************************************************************************/


    /**
     * 创建黑名单
     * @param $room_id int 房间id
     * @param $user_id int 被禁言者ID
     * @param $admin_id int 禁言操作者ID
     * @return bool
     */
    public function add_block($room_id, $user_id,$admin_id){

        //如果已禁言，则禁止重复操作
        if($this->get_block($room_id,$user_id)){
            return true;
        }

        $data = [
            'room_id'=>$room_id,
            'user_id'=>$user_id,
            'admin_id'=>$admin_id,
            'create_timestamp' => time()
        ];
        $result = DB::table("room_block")->insert($data);
        return $result;
    }

    /**
     * 删除黑名单
     * @param $room_id
     * @param $user_id
     * @return int
     */
    public function del_block($room_id, $user_id){
        $result = DB::table("room_block")
            ->where("room_id", "=", $room_id)
            ->where("user_id", "=", $user_id)
            ->delete();
        return $result;
    }

    /**
     * 获取黑名单列表
     * @param $room_id
     * @return array
     */
    public function get_blocks($room_id){
        $blocks = DB::table('room_block')
            ->where('room_block.room_id', $room_id)
            ->get(['room_block.user_id as user_id']);
        $result = self::objToArray($blocks);
        return $result;
    }


    /**
     * 获取黑名单列表 limit
     * @param $room_id
     * @param $offset
     * @param $limit
     * @return mixed
     */
    public function get_blocks_limit($room_id, $offset, $limit){
        $blocks = DB::table('room_block')
            ->where('room_id', $room_id)
            ->offset($offset)
            ->limit($limit)
            ->get(['user_id', 'admin_id', 'create_timestamp']);
        $result = self::objToArray($blocks);
        return $result;
    }


    /**
     * 获取黑名单数量
     * @param $room_id
     * @return int
     */
    public function get_blocks_count($room_id){
        $blocks_count = DB::table('room_block')
            ->where('room_block.room_id', $room_id)
            ->count();
        return $blocks_count;
    }

    /**
     * 获取当前用户是否屏蔽
     * @param $room_id
     * @param $user_id
     * @return true
     */
    public function get_block($room_id, $user_id){
        $result = DB::table("room_block")
            ->where("room_id", $room_id)
            ->where("user_id", $user_id)
            ->first();
        if (empty($result)){
            return false;
        }
        return true;
    }


    /******************************收藏*******************************************************************************/


    /**
     * 添加到收藏哟
     * @param $room_id
     * @param $user_id
     * @return bool
     */
    public function add_collect($room_id, $user_id){
        $data = [
            'room_id'=>$room_id,
            'user_id'=>$user_id,
            'create_timestamp' => time()
        ];
        $result = DB::table("room_collect")->insert($data);
        return $result;
    }

    /**
     * 取消收藏
     * @param $room_id
     * @param $user_id
     * @return int
     */
    public function del_collect($room_id, $user_id){
        /*$room = $this->get_room($room_id);
        if ($room['user_id'] == $user_id){
            return 0;
        }*/
        $result = DB::table("room_collect")
            ->where("room_id", "=", $room_id)
            ->where("user_id", "=", $user_id)
            ->delete();
        return $result;
    }

    /**
     * 获取用户收藏列表
     * @param $user_id
     * @return array
     */
    public function get_collects($user_id){
        $collects = DB::table('room_collect')
            ->leftjoin('room', 'room_collect.room_id', 'room.room_id')
            ->leftJoin("room_type", "room.room_type", "=", "room_type.type_id")
            ->leftJoin("room_level", "room.level", "=", "room_level.id")
            ->leftJoin("room_union_level", "room.union_level", "=", "room_union_level.id")
            ->where('room_collect.user_id', $user_id)
            ->get($this->sql_room_fields);
        $result = self::objToArray($collects);
        for ($i = 0; $i < count($result); $i++){
            $result[$i]["room_type"] = [];
            if(!$result[$i]["name"]) $result[$i]["name"] = self::DEFAULT_ROOM_NAME;
            $result[$i]["room_type"]["id"] = $result[$i]["type_id"];
            $result[$i]["room_type"]["type_name"] = $result[$i]["type_name"];
            $result[$i]["room_type"]["img_home_url"] = build_image($result[$i]["img_home_url"]);
            $result[$i]["room_type"]["img_room_url"] = build_image($result[$i]["img_room_url"]);
            $result[$i]["room_type"]["img_roomedit_url"] = build_image($result[$i]["img_roomedit_url"]);
            $result[$i]["background_pic"] = build_image($result[$i]["background_pic"]);

            if(!$result[$i]['image']) $result[$i]['image'] = '/room/image_default.png';
            //图片尺寸适配
            $result[$i]['adapt_image'] = build_adapt_images($result[$i]["image"] ,$this->adapt_size);

            $result[$i]["image"] = build_image($result[$i]["image"]);
            $result[$i]["level_icon"] = build_image($result[$i]["level_icon"]);
            $result[$i]["union_level_icon"] = build_image($result[$i]["union_level_icon"]);
            $result[$i]["game_area"] = $result[$i]["game_area"] ? explode(",", $result[$i]["game_area"]) : [];
            $result[$i]["game_level"] = $result[$i]["game_level"] ? explode(",", $result[$i]["game_level"]) : [];
            $result[$i]["game_desc"] = (!empty($result[$i]["game_area"]) && !empty($result[$i]["game_level"])) ? $result[$i]["game_area"][0] . "|" . implode("/", $result[$i]["game_level"]) : "";


//            unset($result[$i]["type_id"]);
            unset($result[$i]["type_name"]);
            unset($result[$i]["img_home_url"]);
            unset($result[$i]["img_room_url"]);
            unset($result[$i]["img_roomedit_url"]);
        }
        return $result;
    }


    /**
     * 获取用户收藏列表 limit
     * @param $user_id
     * @param $offset
     * @param $limit
     * @return mixed
     */
    public function get_collects_limit($user_id, $offset, $limit){
        $collects = DB::table('room_collect')
            ->leftjoin('room', 'room_collect.room_id', 'room.room_id')
            ->leftJoin("room_type", "room.room_type", "=", "room_type.type_id")
            ->leftJoin("room_level", "room.level", "=", "room_level.id")
            ->leftJoin("room_union_level", "room.union_level", "=", "room_union_level.id")
            ->leftJoin("room_tag", "room.room_tag_id", "=", "room_tag.id")
            ->where('room_collect.user_id', $user_id)
            ->offset($offset)
            ->limit($limit)
            ->get($this->sql_room_fields);
        $result = self::objToArray($collects);
        for ($i = 0; $i < count($result); $i++){
            $result[$i]["room_type"] = [];
            if(!$result[$i]["name"]) $result[$i]["name"] = self::DEFAULT_ROOM_NAME;
            $result[$i]["room_type"]["id"] = $result[$i]["type_id"];
            $result[$i]["room_type"]["type_name"] = $result[$i]["type_name"];
            $result[$i]["room_type"]["img_home_url"] = build_image($result[$i]["img_home_url"]);
            $result[$i]["room_type"]["img_room_url"] = build_image($result[$i]["img_room_url"]);
            $result[$i]["room_type"]["img_roomedit_url"] = build_image($result[$i]["img_roomedit_url"]);
            $result[$i]["background_pic"] = build_image($result[$i]["background_pic"]);

            //图片尺寸适配
            $result[$i]['adapt_image'] = build_adapt_images($result[$i]["image"] ,$this->adapt_size);

            if(!$result[$i]['image']) $result[$i]['image'] = '/room/image_default.png';
            $result[$i]["image"] = build_image($result[$i]["image"]);
            $result[$i]["level_icon"] = build_image($result[$i]["level_icon"]);
            $result[$i]["union_level_icon"] = build_image($result[$i]["union_level_icon"]);
            $result[$i]["game_area"] = $result[$i]["game_area"] ? explode(",", $result[$i]["game_area"]) : [];
            $result[$i]["game_level"] = $result[$i]["game_level"] ? explode(",", $result[$i]["game_level"]) : [];
            $result[$i]["game_desc"] = (!empty($result[$i]["game_area"]) && !empty($result[$i]["game_level"])) ? $result[$i]["game_area"][0] . "|" . implode("/", $result[$i]["game_level"]) : "";

//            unset($result[$i]["type_id"]);
            unset($result[$i]["type_name"]);
            unset($result[$i]["img_home_url"]);
            unset($result[$i]["img_room_url"]);
            unset($result[$i]["img_roomedit_url"]);
        }
        return $result;
    }


    /**
     * 获取用户收藏数量
     * @param $user_id
     * @return int
     */
    public function get_collects_count($user_id){
        $collects_count = DB::table('room_collect')
            ->where('room_collect.user_id', $user_id)
            ->count();
        return $collects_count;
    }

    /**
     * 获取当前房间是否收藏
     * @param $room_id
     * @param $user_id
     * @return int
     */
    public function get_collect($room_id, $user_id){
        $result = DB::table("room_collect")
            ->where("room_id", $room_id)
            ->where("user_id", $user_id)
            ->first();
        if (empty($result)){
            return false;
        }
        return true;
    }


    /**
     * 获取房间收藏的用户ID列表
     * @param $room_id
     * @return mixed
     */
    public function get_collect_users($room_id){
        $result = DB::table("room_collect")
            ->where("room_id", $room_id)
            ->get();
        return self::objToArray($result);
    }


    /**
     * 设置认证
     * @param $room_id
     * @param $val
     * @return int|void
     */
    public function set_cert($room_id, $val){
        $result = DB::table('room')
            ->where('room.room_id', $room_id)
            ->update(['certified'=>$val]);
        $this->delCache($room_id);
        return $result;
    }

    /**
     * 设置标题
     * @param $room_id
     * @param $name
     * @param int $apiType 访问方式 0=api ,1=cms
     * @return int
     */
    public function set_name($room_id, $name,$apiType = 0){
        // 查询房间数据
        $roomData = $this->get_room($room_id);
        $roomData['business_type'] = $roomData['business_type'] ?? 0;

        // 判断房间名称是否变化，无变化直接返回 true
        if($roomData['name'] == $name){
            return true;
        }

        // redisKey
        $redisKeyRoomNameUpdateLimit = $this->redisKeyRoomNameUpdateLimit . date('Y-m-d');

        // TODO 商业类型（0=小屋 1=CBD）【类型为CBD的限制】
        if($roomData['business_type'] == 1 and $apiType == 0) {
            // 获取cache房间名称修改次数
            if (Redis::hexists($redisKeyRoomNameUpdateLimit, $room_id)) {
                $limitNumber = Redis::HGET($redisKeyRoomNameUpdateLimit, $room_id);
                if ($limitNumber >= 3) {
                    return 'SET_NAME_FALSE';
                }
            }
        }

        // 更新房间名称
        $result = DB::table('room')
            ->where('room.room_id', $room_id)
            ->update(['name'=>$name]);

        // 删除房间缓存数据
        $this->delCache($room_id);

        // TODO 商业类型（0=小屋 1=CBD）【类型为CBD的限制】
        if($roomData['business_type'] == 1 and $apiType == 0) {
            // 设置每日房间名称修改次数
            Redis::HINCRBY($redisKeyRoomNameUpdateLimit, $room_id, 1);
            if (Redis::TTL($redisKeyRoomNameUpdateLimit) == -1) {
                Redis::EXPIRE($redisKeyRoomNameUpdateLimit, 25 * 3600);
            }
        }

        return $result;
    }

    /**
     * 设置公告
     * @param $room_id
     * @param $notice
     * @return int
     */
    public function set_notice($room_id, $notice){
        $result = DB::table('room')
            ->where('room.room_id', $room_id)
            ->update(['notice'=>$notice]);
        $this->delCache($room_id);
        return $result;
    }

    /**
     * 房间封面审核（记录到图片审核表中）
     * */
    public function roomImageExamine($room_id, $image){
        $picHost = parse_url(getPicDomain(), PHP_URL_HOST);
        $urlArray = parse_url($image);
        if(!empty($urlArray['path']) and !empty($urlArray['host'])){
            if ($picHost == $urlArray['host']){
                $image = $urlArray['path'];
            }
        }

        // 查询房间数据
        $roomData = $this->get_room($room_id);
        $roomData['business_type'] = $roomData['business_type'] ?? 0;

        // 判断房间图片是否变化，无变化直接返回 true
        if($roomData['image'] == $image){
            return true;
        }

        // TODO 商业类型（0=小屋 1=CBD）【类型为小屋的直接更改数据】
        if($roomData['business_type'] == 0) {
            return $this->set_image($room_id,$image);
        }

        // [type] 数据类型 0=房间图片 ...
        // [status] 审核状态 0=未审核 1=已审核 2=驳回

        // TODO 判断当日所有更新次数是否达上限
        $checkImageData = $this->getRoomImageExamine(['room_id' => $room_id, 'type' => 0, 'date' => date('Ymd')],false);
        $updateNumber = 0;
        foreach ($checkImageData as $value){
            $updateNumber += $value['update_number'];
        }
        if(!empty($checkImageData) and $updateNumber >= 2){
            return 'ROOM_IMAGE_EXAMINE_FALSE';
        }

        // TODO 查询当天内是否存在未审核的图片数据
        $checkImageData = $this->getRoomImageExamine(['room_id' => $room_id, 'type' => 0, 'status' => 0 ,'date' => date('Ymd')]);
        if(!empty($checkImageData)){

            // 判断图片数据不一致，则更新为最新图片地址
            if($checkImageData['image'] != $image){
                DB::table('image_examine')->where(['id' => $checkImageData['id'],'room_id' => $room_id])->increment('update_number', 1, [
                    'image' => $image,
                    'updated_at' => time(),
                ]);
            }
            return true;
        }else{
            // TODO 查询是否存在未审核的图片数据
            $checkImageData = $this->getRoomImageExamine(['room_id' => $room_id, 'type' => 0, 'status' => 0]);
            if(!empty($checkImageData)) {

                // 更新之前的日期为当天日期、图片、更新次数重置为1
                DB::table('image_examine')->where(['id' => $checkImageData['id'],'room_id' => $room_id])->update([
                    'image' => $image,
                    'update_number' => 1,
                    'date' => date('Ymd'),
                    'updated_at' => time(),
                ]);
                return true;
            }
        }

        // 创建图片审核数据
        $result = DB::table('image_examine')->insert([
            'room_id' => $room_id,
            'image' => $image,
            'type' => 0,
            'status' => 0,
            'date' => date('Ymd'),
            'created_at' => time(),
            'updated_at' => time(),
        ]);
        return $result;
    }

    /**
     * 查询房间封面审核数据
     * */
    public function getRoomImageExamine($condition, $single = true){
        $field = ['id', 'room_id', 'image','update_number'];
        if($single) {
            $data = DB::table('image_examine')->where($condition)->first($field);
        }else{
            $data = DB::table('image_examine')->where($condition)->get($field)->toArray();
        }
        return self::objToArray($data);
    }

    /**
     * 更新房间封面审核数据
     * */
    public function updateRoomImageExamine($id,$roomId,$status,$remark){
        // 查询未审核的房间图片数据
        $result = DB::table('image_examine')
            ->where(['id'=>$id,'room_id' => $roomId, 'type' => 0, 'status' => 0])
            ->update([
                'status' => $status,
                'remark' => $remark,
                'updated_at' => time()
            ]);
        return $result;
    }

    /**
     * 设置图片 (将真实更新到房间数据表中)
     * @param $room_id
     * @param $image
     * @return int
     */
    public function set_image($room_id, $image){
        $pic_host = parse_url(getPicDomain(), PHP_URL_HOST);
        $uri_arr = parse_url($image);
        if(!empty($uri_arr['path']) && !empty($uri_arr['host'])){
            if ($pic_host == $uri_arr['host']){
                $image = $uri_arr['path'];
            }
        }
        // 处理后缀
        $arrExt = explode('!', $image);
        if (count($arrExt) > 1){
            $image = $arrExt[0];
        }
        $result = DB::table('room')
            ->where('room.room_id', $room_id)
            ->update(['image'=>$image]);
        $this->delCache($room_id);
        return $result;
    }

    /**
     * 设置房间背景图片
     * @param $room_id
     * @param $pic_url
     * @return int
     */
    public function set_background_pic($room_id, $pic_url){
        $uri_arr = parse_url($pic_url);
        if(!empty($uri_arr['path'])){
            $pic_url = $uri_arr['path'];
        }
        // 处理后缀
        $arrExt = explode('!', $pic_url);
        if (count($arrExt) > 1){
            $pic_url = $arrExt[0];
        }
        $result = DB::table('room')
            ->where('room.room_id', $room_id)
            ->update(['background_pic' => $pic_url]);
        $this->delCache($room_id);
        return $result;
    }

    /**
     * 设置公告
     * @param int $room_id
     * @param string $desc
     * @return int
     */
    public function set_desc(int $room_id, string $desc){
        $result = DB::table('room')
            ->where('room.room_id', $room_id)
            ->update(['desc'=>$desc]);
        $this->delCache($room_id);
        return $result;
    }


    /**
     * 设置Uid
     * @param int $roomId
     * @param string $uid
     * @return int
     */
    public function setUid(int $roomId, string $uid){
        $result = DB::table('room')
            ->where('room_id', $roomId)
            ->update(['room_uid'=>$uid]);
        $this->delCache($roomId);
        return $result;
    }

    /**
     * 获取背景图片列表
     * @return mixed
     */
    public function get_backgrounds(){
        $backgrounds = DB::table("room_background")->get();
        $result = self::objToArray($backgrounds);
        for ($i = 0; $i < count($result); $i++){
            $result[$i]["pic_url"] = build_image($result[$i]["pic_url"]);
            $result[$i]["preview_url"] = build_image($result[$i]["preview_url"]);
            $result[$i]["preview_radio_url"] = build_image($result[$i]["preview_radio_url"]);
        }
        return $result;
    }

    /**
     * 获取房间 的背景图片列表
     *
     * Created at 2021/11/15 09:56
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param int $roomId
     * @return array
     */
    public function get_backgrounds_v2(int $roomId): array
    {
        $result = BackgroundPictureManagement::getRoomResources($roomId);
        $list = [];
        foreach ($result as $item) {

            //根据时间过滤
            if(!empty($item['start_time']) && time() < $item['start_time']){
                continue;
            }
            if(!empty($item['end_time']) && time() > $item['end_time']){
                continue;
            }

            $resourceUrl = build_image($item['resource_url']);
            $resourceUrl2 = build_image($item['resource_url2']);
            $list[] = [
                'id' => $item['id'],
                'name' => '',
                'pic_url' => $resourceUrl,
                'preview_url' => build_image('/room/background/preview.png'),
                'preview_radio_url' => $resourceUrl,
                'pic_url2' => $resourceUrl2,
            ];
        }

        return array_merge($list, $this->get_backgrounds());
    }


    /**
     * 踢出添加用户
     * @param $room_id
     * @param $user_id
     * @param $time (S)
     * @return bool
     */
    public function add_shotoff($room_id, $user_id, $time){
        $key = $this->redis_shot_off . $room_id . '-' . $user_id;
        Redis::SET($key, time(), 'EX', $time);
        return true;
    }


    /**
     * 添加踢人日志
     * @param $roomId
     * @param $userId
     * @param $shotoffUserId
     */
    public function add_shotoff_log($roomId, $userId, $shotoffUserId){
        DB::table('room_shotoff_log')->insert([
            'user_id' => $userId,
            'shotoff_user_id' => $shotoffUserId,
            'room_id' => $roomId,
            'create_timestamp' => time()
        ]);
    }


    /**
     * 获取踢人日志
     * @param $roomId
     * @param $userId
     * @param $shotoffUserId
     */
    public function getShotoffLog($roomId){
        $result = DB::table('room_shotoff_log')
            ->where([
                ['room_id' ,'=', $roomId],
//                ['create_timestamp', '>', time()-3*24*3600]
            ])
            ->orderBy('create_timestamp', 'desc')
            ->get(['user_id', 'shotoff_user_id', 'create_timestamp']);
        $result = self::objToArray($result);
        return $result;
    }



    /**
     * 查看是否踢出状态
     * @param $room_id
     * @param $user_id
     * @return bool
     */
    public function get_shotoff($room_id, $user_id){
        $key = $this->redis_shot_off . $room_id . '-' . $user_id;
        $ret = Redis::GET($key);
        if (empty($ret)){
            return false;
        }
        return true;
    }

    /**
     * 删除用户房间踢出状态
     * @param $room_id
     * @param $user_id
     * @return bool
     */
    public function del_shotoff($room_id, $user_id){
        $key = $this->redis_shot_off . $room_id . '-' . $user_id;
        $ret = Redis::DEL($key);
        return true;
    }

    /**
     * 获取分类
     * @param int $certified -1 获取全(部默认值) 0 非认证 1 认证房间
     * @return array
     */
    public function get_room_types($certified = -1){
        $room_types = null;
        if ($certified == 0){
            $room_types = DB::table("room_type")
                ->where('certified', '=', 0)
                ->where('is_show', '=', 1)
                ->orderBy('sort','DESC')->get();
        }else if ($certified == 1) {
            $room_types = DB::table("room_type")
                ->where('certified', '=', 1)
                ->where('is_show', '=', 1)
                ->orderBy('sort', 'DESC')->get();
        }else{
            $room_types = DB::table("room_type")
                ->where('is_show', '=', 1)
                ->orderBy('sort','DESC')->get();
        }

        $result = self::objToArray($room_types);
        $data = [];

        foreach ($result as $k => $v){
            $v['id'] = $v['type_id'];
            if ($v['type_id'] == 0){
                continue;
            }
            if (!empty($v['img_home_url'])){
                $v['img_home_url'] =  build_image($v['img_home_url']);
            }
            if (!empty($v['img_room_url'])){
                $v['img_room_url'] =  build_image($v['img_room_url']);
            }
            if (!empty($v['img_roomedit_url'])){
                $v['img_roomedit_url'] =  build_image($v['img_roomedit_url']);
            }
            if (!empty($v['img_cbd_url'])){
                $v['img_cbd_url'] =  build_image($v['img_cbd_url']);
            }
            if ($v['type_id'] == 1){
                $v['allow_setting'] = false;
            }
            else{
                $v['allow_setting'] = true;
            }
            unset($v['type_id']);
            $data[] = $v;
        }

        return $data;
    }

    /**
     * @desc 获取房间分类简版
     * @author zxiaofee
     * @param int $certified -1 获取全(部默认值) 0 非认证 1 认证房间
     * @return array
     */
    public function get_room_types_simple($certified = -1){
        $room_types = null;
        $fields = ['type_id', 'type_name'];
        if ($certified == 0){
            $room_types = DB::table("room_type")
                ->where('certified', '=', 0)
                ->where('is_show', '=', 1)
                ->orderBy('sort','DESC')->get($fields);
        }else if ($certified == 1) {
            $room_types = DB::table("room_type")
                ->where('certified', '=', 1)
                ->where('is_show', '=', 1)
                ->orderBy('sort', 'DESC')->get($fields);
        }else{
            $room_types = DB::table("room_type")
                ->where('is_show', '=', 1)
                ->orderBy('sort','DESC')->get($fields);
        }

        $room_types = self::objToArray($room_types);

        foreach ($room_types as $k => $v){
            if ($v['type_id'] == 0){
                unset($room_types[$k]);
            } else {
                $room_types[$k]['id'] =  $v['type_id'];
                unset($room_types[$k]['type_id']);
            }
        }
        $room_types = array_values($room_types);
        return $room_types;
    }

    public function getRoomType($typeId){
        $type = DB::table("room_type")
            ->where('type_id', '=', $typeId)
            ->first();
        if (empty($type)){
            return null;
        }
        $result = self::objToArray($type);
        $result['id'] = $result['type_id'];
        if (!empty($result['img_home_url'])){
            $result['img_home_url'] =  build_image($result['img_home_url']);
        }
        if (!empty($result['img_room_url'])){
            $result['img_room_url'] =  build_image($result['img_room_url']);
        }
        if (!empty($result['img_roomedit_url'])){
            $result['img_roomedit_url'] =  build_image($result['img_roomedit_url']);
        }
        if (!empty($result['img_cbd_url'])){
            $result['img_cbd_url'] =  build_image($result['img_cbd_url']);
        }
        if (!empty($result['default_background_pic'])){
            $result['default_background_pic'] =  build_image($result['default_background_pic']);
        }
        if ($result['type_id'] == 1){
            $result['allow_setting'] = false;
        }
        else{
            $result['allow_setting'] = true;
        }
        unset($result['type_id']);
        return $result;
    }

    /**
     * 房间首页图标列表
     * @return mixed
     */
    public function get_room_home_icons(){
        $room_types = DB::table("room_home_icon")->get();
        $result = self::objToArray($room_types);
        for ($i = 0; $i < count($result); $i++){
            if (!empty($result[$i]['icon_url'])){
                $result[$i]['icon_url'] =  build_image($result[$i]['icon_url']);
            }
            if (!empty($result[$i]['icon_cur_url'])){
                $result[$i]['icon_cur_url'] =  build_image($result[$i]['icon_cur_url']);
            }
        }
        return $result;
    }


    /**
     * @return mixed
     */
    public function generated_uid(){

        if (!Redis::EXISTS($this->redis_room_uid_lianghao)){
            $file = fopen('../storage/lianghao/0001.txt', "r");
            $arr_uid = [];
            while (!feof($file)){
                $uid = fgets($file);
                if (!empty($uid)){
                    $arr_uid[intval($uid)] = 0;
                }
            }
            Redis::HMSET($this->redis_room_uid_lianghao, $arr_uid);
        }

        if (!Redis::EXISTS($this->redis_room_uid_index)){
            Redis::SET($this->redis_room_uid_index, 10000);
        }
        $uid = Redis::INCR($this->redis_room_uid_index);
        if (Redis::HEXISTS($this->redis_room_uid_lianghao, $uid)){
            return $this->generated_uid();
        }
        return $uid;
    }


    /**
     * 添加房间举报
     * @param $user_id         举报人ID
     * @param $report_room_id  被举报ID
     * @param $report_type     举报类型 1.色情 2.广告 3.诈骗 4.侮辱诋毁 5其他原因
     * @param $pics            图片 字符json
     * @param $describe        举报说明
     */
    public function add_report($user_id, $report_room_id, $report_type, $pics, $describe){
        $pic_arr = explode(",", $pics);
        $images = [];
        for ($i=0; $i<count($pic_arr); $i++){
            $uri_arr = parse_url($pic_arr[$i]);
            if(!empty($uri_arr['path'])){
                $images[] = $uri_arr['path'];
            }
        }
        $pics = json_encode($images);

        DB::table("room_report")
            ->insert(["user_id"=>$user_id, "report_room_id"=>$report_room_id, "report_type"=>$report_type, "pics"=>$pics, "describe"=>$describe, 'create_timestamp' => time()]);
    }


    /**
     * 获取主播所在房间
     * 该方法有问题，弃用
     */
    /*
    public function get_anchor_rooms(){
        $fields = $this->sql_room_fields;
        $fields[] = 'room_role.role_type as role_type';
        $fields[] = 'room_role.user_id as role_user_id';
        $rooms = DB::table('room_role')
            ->leftJoin('room', "room_role.room_id", "=", "room.room_id")
            ->leftJoin("room_type", "room.room_type", "=", "room_type.type_id")
            ->where('room.room_type', '<>', 0)
            ->get($fields);
        $result = self::objToArray($rooms);
        for ($i = 0; $i < count($result); $i++){
            $result[$i]["room_type"] = [];
            $result[$i]["room_type"]["id"] = $result[$i]["type_id"];
            $result[$i]["room_type"]["type_name"] = $result[$i]["type_name"];
            $result[$i]["room_type"]["img_home_url"] = build_image($result[$i]["img_home_url"]);
            $result[$i]["room_type"]["img_room_url"] = build_image($result[$i]["img_room_url"]);
            $result[$i]["room_type"]["img_roomedit_url"] = build_image($result[$i]["img_roomedit_url"]);
            $result[$i]["background_pic"] = build_image($result[$i]["background_pic"]);
            $result[$i]["image"] = build_image($result[$i]["image"]);
//            unset($result[$i]["type_id"]);
            unset($result[$i]["type_name"]);
            unset($result[$i]["img_home_url"]);
            unset($result[$i]["img_room_url"]);
            unset($result[$i]["img_roomedit_url"]);
        }
        return $result;
    }
    */

    /**
     * 设置房间类型
     * @param int $room_id      房间ID
     * @param int $type         房间类型 0.普通房间 1.电台房间 2.交友 3.情感 4.娱乐
     * @return int
     */
    public function set_room_type(int $room_id,int $type){
        $result = DB::table('room')
            ->where('room_id', $room_id)
            ->update(['room_type' => $type]);
        $this->delCache($room_id);
        return $result;
    }

    /**
     * 设置房间标签ID
     * */
    public function setRoomTagId($roomId,$roomTagId){
        $result = DB::table('room')
            ->where('room_id', $roomId)
            ->update(['room_tag_id' => $roomTagId]);
        $this->delCache($roomId);
        return $result;
    }


    public function delCache($roomId){
        Redis::DEL($this->redis_room_cache . $roomId);
        $search = new Search();
        $search->delRoom($roomId);
    }

    public function delRedisCache($roomId){
        Redis::DEL($this->redis_room_cache . $roomId);
    }

    /**
     * 获取房间分类下的所有标签
     * */
    public function getRoomTagListByRoomType($roomTypeId){
        $result = DB::table('room_tag')->where(['room_type_id' => $roomTypeId,'status' => 1])->get(['id as tag_id','room_type_id','tag_name','tag_color'])->toArray();
        $result = self::objToArray($result);
        return $result;
    }

    /**
     * 删除中数据
     * @param $room_id
     */
    public function del_open_data($room_id){
        $key = $this->redis_room . $room_id;
        Redis::DEL($key);
        $this->del_opened($room_id);
    }

    /**
     * 设置房间关闭时间
     * @param $room_id
     * @param $timestamp
     */
    public function set_close_timestamp($room_id, $timestamp){
        $key = $this->redis_room . $room_id;
        Redis::HSET($key, 'close_timestamp', $timestamp);
    }

    /**
     * 获取房间关闭时间
     * @param $room_id
     * @return int|null
     */
    public function get_close_timestamp($room_id){
        $key = $this->redis_room . $room_id;
        $data = Redis::HGET($key, 'close_timestamp');
        if (empty($data)){
            return null;
        }
        /*if (intval($data) < time()){
            $this->del_open_data($room_id);
            return null;
        }*/
        return intval($data);
    }

    /**
     * 删除房间关闭时间
     * @param $room_id
     * @return int|null
     */
    public function del_close_timestamp($room_id){
        $key = $this->redis_room . $room_id;
        Redis::HDEL($key, 'close_timestamp');
    }


    /**
     * 标记房间是开启 如果关闭则删除
     * @param $room_id
     */
    public function set_opened($room_id){
        $key = $this->redis_room . $room_id;
        Redis::HSET($key, 'opened', 1);
        Redis::HSET($this->redis_room_opened, $room_id, time());

    }

    /**
     * 获取房间是否开启
     * @param $room_id
     * @return mixed
     */
    public function get_opened($room_id){
        $key = $this->redis_room . $room_id;
        $data = Redis::HGET($key, 'opened');
        if ($data == 1){
            return true;
        }
        return false;
    }


    /**
     * 设置声网aig
     * @param $roomId
     */
    public function setAig($roomId) {
        $key = $this->redis_room . $roomId;
        Redis::HSET($key, 'aig', 1);
    }


    /**
     * 获取声网Aig
     * @param $roomId
     * @return bool
     */
    public function getAig($roomId){
        $key = $this->redis_room . $roomId;
        $data = Redis::HGET($key, 'aig');
        if ($data == 1){
            return true;
        }
        return false;
    }




    /**
     * 获取开启的房间列表
     * @return mixed
     */
    public function getOpenedRoomIdArr(){
        $roomIdArr = Redis::HKEYS($this->redis_room_opened);
        return $roomIdArr;
    }


    /**
     * 删除房间开启状态
     * @param $room_id
     */
    public function del_opened($room_id){
        $key = $this->redis_room . $room_id;
        Redis::HDEL($key, 'opened');
        Redis::HDEL($this->redis_room_opened, $room_id);
    }

    /**获取房间开启时间
     * @param $room_id
     * @return mixed
     */
    public function get_opened_time($room_id){
        return Redis::HGET($this->redis_room_opened, $room_id);
    }


    /**
     * 添加房间到待删除列表
     * @param $room_id
     */
    public function add_wait_close($room_id){
        Redis::LPUSH($this->redis_room_wait, $room_id);
    }
    public function radd_wait_close($room_id){
        Redis::RPUSH($this->redis_room_wait, $room_id);
    }


    /**
     * 待删除列表获取一个房间
     * @return mixed
     */
    public function pop_wait_close(){
        return Redis::RPOP($this->redis_room_wait);
    }

    /**
     * 获取已认证房间
     * @return mixed
     */
    public function get_certified(){
        $rr = $this->where(['certified' => 1])
            ->get(['room_id','user_id','room_rate'])
            ->toArray();
        return $rr;
    }

    /**
     * 房间是否认证
     * @param $room_id
     * @return int
     */
    public function is_certified($room_id){
        $document = DB::table('room')->where(['room_id' => $room_id])->first(['certified']);
        $res = self::objToArray($document);
        return $res['certified'];
    }

    /**
     * 设置房间密码
     * @param $room_id
     * @param $password
     */
    public function set_password($room_id, $password){
        $key = $this->redis_room . $room_id;
        $data = Redis::HSET($key, 'password', $password);
    }

    /**
     * 获取房间密码
     * @param $room_id
     * @return null
     */
    public function get_password($room_id){
        $key = $this->redis_room . $room_id;
        $data = Redis::HGET($key, 'password');
        return $data;
    }

    /**
     * 清除房间密码
     * @param $room_id
     */
    public function del_password($room_id){
        $key = $this->redis_room . $room_id;
        Redis::HDEL($key, 'password');
    }


    /**
     * 设置房间是否自由麦
     * @param $room_id
     * @param $freemicro
     */
    public function set_freemicro($room_id, $free_micro){
        $key = $this->redis_room . $room_id;
        $data = Redis::HSET($key, 'free_micro', $free_micro);
    }

    /**
     * 获取房间是否自由麦
     * @param $room_id
     * @return null
     */
    public function get_freemicro($room_id){
        $key = $this->redis_room . $room_id;
        $data = Redis::HGET($key, 'free_micro');
        if ($data === null){
            return 1;
        }
        return $data;
    }

    /**
     * 清除房间是否自由麦
     * @param $room_id
     */
    public function del_freemicro($room_id){
        $key = $this->redis_room . $room_id;
        Redis::HDEL($key, 'free_micro');
    }



    /**
     * 设置房间模式类型
     * @param $room_id
     * @param $freemicro
     */
    public function setModeType($roomId, $type){
        $key = $this->redis_room . $roomId;
        $data = Redis::HSET($key, 'mode_type', $type);
    }

    /**
     * 获取房间模式类型 0.娱乐模式、1.天籁模式、2.高音质
     * @param $room_id
     * @return null
     */
    public function getModeType($roomId){
        $key = $this->redis_room . $roomId;
        $data = Redis::HGET($key, 'mode_type');
        if (empty($data)){
            return 0;
        }
        return $data;
    }

    /**
     * 删除房间模式类型
     * @param $room_id
     */
    public function delModeType($roomId){
        $key = $this->redis_room . $roomId;
        Redis::HDEL($key, 'mode_type');
    }





    /**
     * 设置聊天屏是否启用
     * @param $room_id
     * @param $opened 0.关闭 1.开启
     */
    public function set_screen_opened($room_id, $opened){
        $key = $this->redis_room . $room_id;
        $data = Redis::HSET($key, 'screen_opened', $opened);
    }

    /**
     * 获取聊天屏幕是否启用
     * @param $room_id
     * @return int  0.关闭 1.开启
     */
    public function get_screen_opened($room_id){
        $key = $this->redis_room . $room_id;
        $data = Redis::HGET($key, 'screen_opened');
        if ($data === null){
            return 1;
        }
        return intval($data);
    }

    /**
     * 聊天屏幕是否启用标记删除
     * @param $room_id
     */
    public function del_screen_opened($room_id){
        $key = $this->redis_room . $room_id;
        Redis::HDEL($key, 'screen_opened');
    }

    /**
     * 设置全麦是否关闭
     * @param $room_id
     * @param $closed 0.未关闭,1.关闭
     */
    public function set_volume_closed($room_id, $closed){
        $key = $this->redis_room . $room_id;
        $data = Redis::HSET($key, 'volume_closed', $closed);
    }

    /**
     * 获取全麦是否关闭
     * @param $room_id
     * @return int 0.未关闭,1.关闭
     */
    public function get_volume_closed($room_id){
        $key = $this->redis_room . $room_id;
        $data = Redis::HGET($key, 'volume_closed');
        if ($data === null){
            return 0;
        }
        return intval($data);
    }


    /**
     * 设置求陪伴
     * @param $room_id
     * @return mixed
     */
    public function setAccompanyTag($room_id){
        $key = $this->redis_room . $room_id;
        $data = Redis::HSET($key, 'accompany_tag', 1);
        return $data;
    }

    /**
     * 删除求陪伴
     * @param $room_id
     * @return mixed
     */
    public function delAccompanyTag($room_id){
        $key = $this->redis_room . $room_id;
        $data = Redis::HDEL($key, 'accompany_tag');
        return $data;
    }

    /**
     * 获取是否求陪伴
     * @param $room_id
     * @return bool
     */
    public function getAccompanyTag($room_id){
        $key = $this->redis_room . $room_id;
        $data = Redis::HGET($key, 'accompany_tag');
        if (empty($data)){
            return false;
        }
        return true;
    }


    /**
     * 融云状态代处理队列添加
     */
    public function pushRongCloudWaitQueue($userId, $timestamp){
        Redis::LPUSH('RONGCLOUD:WAIT', $userId . ',' . $timestamp);
    }

    /**
     * 获取一个待处理用户和加入时间
     * @return array [user_id, timestamp]
     */
    public function popRongCloudWaitQueue(){
        $str = Redis::RPOP('RONGCLOUD:WAIT');
        if (empty($str)){
            return null;
        }
        $arr = explode(',', $str);
        return ['user_id' => intval($arr[0]), 'timestamp' => intval($arr[1])];
    }


    /**
     * 设置用户为离线状态
     * @param $userId
     * @param $timestamp
     */
    public function setRongCloudOffline($userId, $timestamp){
        Redis::HSET('RONGCLOUD:OFFLINE', $userId, $timestamp);
        $expiryTime = $timestamp + 1800 * 1000;
        Redis::HSET($this->redis_log_out_key, $userId, $expiryTime);//过期时间为半个小时之后
        $user = (new User())->get_user($userId);
        $gender = $user['gender'];
        if ($gender == 1) {//男
            Redis::HSET($this->redis_man_log_out_key, $userId, $expiryTime);//过期时间为半个小时之后
        } elseif ($gender == 2) {//女
            Redis::HSET($this->redis_women_log_out_key, $userId, $expiryTime);//过期时间为半个小时之后
        }

        $meetUserInfo = (new MeetingServices())->getMeetUserInfo($userId, $userId);
        (new Meet())->setOnlineUserLevelCache($meetUserInfo['level'], $userId);
    }

    /**
     * 获取所有已离线的用户
     *
     * @param int $gender
     * @return array
     */
    public function getLogOutUserIds(int $gender): array
    {
        if ($gender == 1) {
            $userIdArr = Redis::HGETALL($this->redis_man_log_out_key);
        } elseif ($gender == 2) {
            $userIdArr = Redis::HGETALL($this->redis_women_log_out_key);
        } else {
            $userIdArr = Redis::HGETALL($this->redis_log_out_key);
        }

        if (empty($userIdArr)) {
            return [];
        }

        return $userIdArr;
    }

    /**
     * 删除过期的用户
     *
     * @param int $userId
     * @return bool
     */
    public function deleteLogOutUserCache(int $userId): bool
    {
        Redis::HDEL($this->redis_log_out_key, $userId);
        Redis::HDEL($this->redis_man_log_out_key, $userId);
        Redis::HDEL($this->redis_women_log_out_key, $userId);
        return true;
    }

    /**
     * 用户为离线状态时间戳
     * @param $userId
     */
    public function getRongCloudOffline($userId){
        $timestamp = Redis::HGET('RONGCLOUD:OFFLINE', $userId);
        if (empty($timestamp)){
            return null;
        }
        return intval($timestamp);
    }


    /**
     * 删除离线状态
     * @param $userId
     */
    public function delRongCloudOffline($userId){
        Redis::HDEL('RONGCLOUD:OFFLINE', $userId);
    }


    /**
     * 设置房间话题
     * @param $room_id
     * @return mixed
     */
    public function setTopic($room_id, $topic){
        $key = $this->redis_room . $room_id;
        $data = Redis::HSET($key, 'topic', $topic);
        return $data;
    }

    /**
     * 删除房间话题
     * @param $room_id
     * @return mixed
     */
    public function delTopic($room_id){
        $key = $this->redis_room . $room_id;
        $data = Redis::HDEL($key, 'topic');
        return $data;
    }

    /**
     * 获取房间话题
     * @param $room_id
     * @return bool
     */
    public function getTopic($room_id){
        $key = $this->redis_room . $room_id;
        $data = Redis::HGET($key, 'topic');
        if (empty($data)){
            return '';
        }
        return $data;
    }

    /**
     * 语音检查日志
     * @param array $data
     * @return bool
     */
    public function createVoiceCheckLog(array $data) {
        return DB::table('room_voice_check_logs')->insert($data);
    }

    /*
     * 修改语音检查日志状态
     * @param $id
     * @param $status  0未处理  1处理  2忽略
     * @return bool
     * */
    public function updateVoiceCheckLogStatus($id,$status)
    {
        $where['id'] = $id ?? 0;
        $data['status'] = $status ?? 1;
        return DB::table('room_voice_check_logs')->where($where)->update($data);
    }


    /**
     * cms设置团战
     * @param $room_id
     * @param $melee_status  团战0关闭1 开启
     * @return int|void
     */
    public function setMelee($room_id, $melee_status){
        $val['melee'] = $melee_status;
        $result = DB::table('room')
            ->where('room.room_id', $room_id)
            ->update($val);
        $this->delCache($room_id);
        return $result;
    }

    /**
     * cms设置计数
     * @param $room_id
     * @param $tally_status  计数0关闭1 开启
     * @return int|void
     */
    public function setTally($room_id, $tally_status){
        $val['tally'] = $tally_status;
        $result = DB::table('room')
            ->where('room.room_id', $room_id)
            ->update($val);
        $this->delCache($room_id);
        return $result;
    }

    /**
     * 设置房间模式
     * @param $room_id
     * @param $roomMode
     * @return int
     */
    public function setRoomMode($room_id, $roomMode){
        $val['room_mode'] = $roomMode;
        $result = DB::table('room')
            ->where('room.room_id', $room_id)
            ->update($val);

        $this->delCache($room_id);
        return $result;
    }


    public function getHandleRoomList($offset, $limit)
    {
        $result = DB::table('room')
            ->orderBy("room.room_id", "asc")
            ->offset($offset)
            ->limit($limit)
            ->get(["room_id", "name", "notice", "desc"]);
        return $this->objToArray($result);
    }

    /**
     * 获取房间模式
     * @param $room_id
     * @return int
     */
    public function getActionType($room_id){
        $result = Redis::GET($this->redis_room_cache . $room_id);
        $result = json_decode($result, true);

        return $actionType = $result['action_type'] ?? 0;
    }

    public function getRoomTypeCate($certified = 0)
    {
        $result = DB::table('room_type_cate')
            ->orderBy("sort", "asc")
            ->get(["cate_id", "title"]);
        return $this->objToArray($result);
    }

    /**
     * 新版获取房间类型
     * @param int $certified -1 获取全(部默认值) 0 非认证 1 认证房间
     * @param array $cateId cate_id 分类ID
     * @return array
     */
    public function getRoomNewTypes($certified = -1, $cateId = 0){
        $room_types = null;
        if ($certified == 0){
            $room_types = DB::table("room_type")
                ->where('certified', '=', 0)
                ->where('is_show', '=', 1);
        }else if ($certified == 1) {
            $room_types = DB::table("room_type")
                ->where('certified', '=', 1)
                ->where('is_show', '=', 1);
        }else{
            $room_types = DB::table("room_type");
        }

        if ($cateId) {
            $room_types = $room_types->where("cate_id", $cateId)->orderBy('sort','DESC')->get();
        } else {
            $room_types = $room_types->orderBy('sort','DESC')->get();
        }



        $result = self::objToArray($room_types);
        foreach ($result as $key => $value) {
            $result[$key]['titles'] = $result[$key]['title'] ? explode(",", $result[$key]['title']) : [];
            $result[$key]['area'] = $result[$key]['area'] ? explode(",", $result[$key]['area']) : [];
            $result[$key]['level'] = $result[$key]['level'] ? explode(",", $result[$key]['level']) : [];
        }


        $data = [];

        foreach ($result as $k => $v){
            $v['id'] = $v['type_id'];
            if ($v['type_id'] == 0){
                continue;
            }
            if (!empty($v['img_home_url'])){
                $v['img_home_url'] =  build_image($v['img_home_url']);
            }
            if (!empty($v['img_room_url'])){
                $v['img_room_url'] =  build_image($v['img_room_url']);
            }
            if (!empty($v['img_roomedit_url'])){
                $v['img_roomedit_url'] =  build_image($v['img_roomedit_url']);
            }
            if (!empty($v['img_cbd_url'])){
                $v['img_cbd_url'] =  build_image($v['img_cbd_url']);
            }
            if ($v['type_id'] == 1){
                $v['allow_setting'] = false;
            }
            else{
                $v['allow_setting'] = true;
            }
            unset($v['type_id']);
            $data[] = $v;
        }

        return $data;
    }

    /**
     * 设置房间Area
     * @param $roomId
     * @param $game_area
     * @return boolean
     * */
    public function setRoomGameArea($roomId, $game_area){
        $result = DB::table('room')
            ->where('room_id', $roomId)
            ->update(['game_area' => $game_area]);
        $this->delCache($roomId);
        return $result;
    }

    /**
     * 设置房间Level
     * @param $roomId
     * @param $game_level
     * @return boolean
     * */
    public function setRoomGameLevel($roomId, $game_level){
        $result = DB::table('room')
            ->where('room_id', $roomId)
            ->update(['game_level' => $game_level]);
        $this->delCache($roomId);
        return $result;
    }

    /**
     * 获取房间类型max type_id
     * @return int
     * */
    public function getRoomTypeLastId(){
        $result = DB::table('room_type')
            ->orderBy("type_id", "desc")
            ->first(["type_id"]);
        if ($result) {
            return $result->type_id + 1;
        } else {
            return false;
        }
    }



    /**
     * 房间类型-创建/更新/删除
     *
     * @param array $data 数据
     * @param string $type 操作类型 默认 insert=创建，update=更新
     * @param int $typeId 主键Id
     * @return bool
     * */
    public function CUDRoomType($data = [], $type = 'insert', $typeId = 0)
    {
        switch ($type) {
            case 'insert':
                $ret = DB::table($this->roomTypeTable)->insert($data);
                break;
            case 'update':
                $ret = DB::table($this->roomTypeTable)->where([$this->roomTypePrimaryKey => $typeId])->update($data);
                break;
            case 'delete':
                $ret = DB::table($this->roomTypeTable)->where([$this->roomTypePrimaryKey => $typeId])->delete();
                break;
            default:
                $ret = false;
                break;
        }
        Redis::del($this->redisRoomFast);
        return $ret;
    }



    /**
     * 统计日用户进入房间
     * @param $roomId
     * @param $userId
     * @return int
     */
    public function setJoinUserId($roomId, $userId)
    {
        $key = sprintf($this->roomJoinSize, $roomId, date('Ymd'), $userId);
        $ret = Redis::PFADD($key, $userId);
        if (Redis::TTL($key) == -1) {
            Redis::EXPIRE($key, 7*24*3600);
        }
        //增加用户拜访房间记录
        $compareTime = Carbon::now()->subHours(24*7);//近7天/小时
        $visitInfo = DB::table($this->visitHistory)->where(['user_id'=>$userId,'visit_id'=>$roomId,'type'=>2])->where('visit_time','>=', $compareTime)->first();
        $visitInfo = self::objToArray($visitInfo);
        if(empty($visitInfo)){
            $insert = [
                'user_id' => $userId,
                'visit_id' => $roomId,
                'type' => 2,//1用户 2=房间
                'count' => 1,
                'visit_time' => date('Y-m-d H:i:s',time()),
                'created_at' => date('Y-m-d H:i:s',time()),
            ];
            DB::table($this->visitHistory)->insert($insert);
        }else{
            DB::table($this->visitHistory)->where('id', $visitInfo['id'])->increment('count',1);
        }
        return $ret;
    }


    /**
     * 统计日新用户进入房间
     * @param $roomId
     * @param $userId
     * @return int
     */
    public function setJoinNewUserId($roomId, $userId)
    {
        $key = sprintf($this->roomJoinSizeNew, $roomId, date('Ymd'), $userId);
        $ret = Redis::PFADD($key, $userId);
        if (Redis::TTL($key) == -1) {
            Redis::EXPIRE($key, 7*24*3600);
        }
        return $ret;
    }


    /**根据类型id 获取详细信息
     * @param $type_ids
     * @return array
     */
    public function getFastTypes(){
        $data = Redis::get($this->redisRoomFast);
        if(empty($data)){
            $room_types = DB::table("room_type")
                ->where('is_show', '=', 1)
                ->where('location','=',1)
                ->orderBy('sort' ,'desc')
                ->get();
            $result = self::objToArray($room_types);
            foreach ($result as $key => $value) {
                $result[$key]['titles'] = $result[$key]['title'] ? explode(",", $result[$key]['title']) : [];
                $result[$key]['area'] = $result[$key]['area'] ? explode(",", $result[$key]['area']) : [];
                $result[$key]['level'] = $result[$key]['level'] ? explode(",", $result[$key]['level']) : [];
            }

            $data = [];

            foreach ($result as $k => $v){
                $v['id'] = $v['type_id'];
                if ($v['type_id'] == 0){
                    continue;
                }
                if (!empty($v['img_home_url'])){
                    $v['img_home_url'] =  build_image($v['img_home_url']);
                }
                if (!empty($v['img_room_url'])){
                    $v['img_room_url'] =  build_image($v['img_room_url']);
                }
                if (!empty($v['img_roomedit_url'])){
                    $v['img_roomedit_url'] =  build_image($v['img_roomedit_url']);
                }
                if (!empty($v['img_room_fast_url'])){
                    $v['img_room_fast_url'] =  build_image($v['img_room_fast_url']);
                }
                if (!empty($v['img_room_fast_url2'])){
                    $v['img_room_fast_url2'] =  build_image($v['img_room_fast_url2']);
                }
                if (!empty($v['img_room_fast_url3'])){
                    $v['img_room_fast_url3'] =  build_image($v['img_room_fast_url3']);
                }
                if (!empty($v['img_cbd_url'])){
                    $v['img_cbd_url'] =  build_image($v['img_cbd_url']);
                }
                if ($v['type_id'] == 1){
                    $v['allow_setting'] = false;
                }
                else{
                    $v['allow_setting'] = true;
                }
                $v['online_num'] = rand(10,100);

                unset($v['type_id']);
                $data[] = $v;
            }
            Redis::set($this->redisRoomFast ,json_encode($data));
            return  $data;
        }
        return json_decode($data,true);
    }

    /**判断是否是游戏房
     * @param $type_id
     * @return bool
     */
    public function getIsGameRoom($type_id){
        if($type_id >=18 && $type_id <=37){
            return true;
        }
        return  false;
    }

    /**获取所有CBD房间的id
     * @return array
     */
    public function getCbdRoomId(){
        $rooms = DB::table($this->table)->where(['business_type'=>1 ,'certified'=>1])->get(["room_id"]);
        $res = $this->objToArray($rooms);
        return empty($res) ? [] : array_column($res,'room_id');
    }

    /**设置CBD房间的开厅时长
     * @param $room_id
     * @param $date
     * @param $total_time
     * @param $more_five_mic_time
     * @param $less_five_mic_time
     * @param $time
     * @return bool
     */
    public function setRoomOpenTime($room_id, $date, $total_time, $more_five_mic_time, $less_five_mic_time,$time){
        $sql = "INSERT INTO zb_{$this->roomOpenTimeTable} 
            (`room_id`,`date`,`total_time`,`more_five_mic_time`,`less_five_mic_time`,`updated_time`) 
            VALUE({$room_id}, {$date},{$total_time}, {$more_five_mic_time} ,{$less_five_mic_time} ,{$time}) 
            ON DUPLICATE KEY UPDATE 
            total_time=total_time+{$total_time}, more_five_mic_time=more_five_mic_time+{$more_five_mic_time}, less_five_mic_time=less_five_mic_time+{$less_five_mic_time} ,updated_time=".time();
        return DB::INSERT($sql);
    }

    /**获取房间的开厅时长
     * @param $room_id
     * @param int $startTime
     * @param int $endTime
     * @return \Illuminate\Support\Collection|mixed
     */
    public function getRoomOnlineTime($room_id ,$startTime=0 ,$endTime=0){
        $startTime = empty($startTime) ? strtotime(date('Y-m-d 00:00:00')) : $startTime;
        $endTime = empty($endTime) ? strtotime(date('Y-m-d 00:00:00', strtotime('+1 day'))) : $endTime;
        $res = DB::table($this->roomOpenTimeTable)
            ->where('room_id' ,$room_id)
            ->where('date','>=',$startTime)
            ->where('date','<',$endTime)
            ->orderBy('date' ,'desc')
            ->get();
        $res = $this->objToArray($res);
        return $res;
    }

    /**
     * 统计房间的开厅时长
     */
    public function getRoomOnlineTimeByTime($room_id, $startTime, $endTime){
        $startTime = strtotime($startTime." 00:00:00");
        $endTime = strtotime($endTime." 23:59:59");
        $res = DB::table($this->roomOpenTimeTable)
            ->where('room_id', $room_id)
            ->where('date', '>=', $startTime)
            ->where('date', '<=', $endTime)
            ->sum("total_time");
        $res = $this->objToArray($res);
        return $res;
    }

    /**获取推荐标签
     * @return array
     */
    public function getRecommendLabel(){
        $res = DB::table($this->table_recommend_label)->get();
        $res = $this->objToArray($res);
        foreach ($res as &$r){
            $r['animate_resource'] = build_image($r['animate_resource']);
        }
        return array_column($res ,null ,'id');
    }

    public function updateCarStatus($room_id ,$params){
        return DB::table($this->table)
            ->where('room_id' ,$room_id)
            ->update($params);
    }

    //私聊记录
    public function insertChatPrivateLog($room_id ,$user_id ,$to_user_id){
        $key = "ROOM:".date('Ymd').":".$room_id.":".$user_id.":".$to_user_id;
        $data = Redis::get($key);
        if(empty($data)){
            Redis::setex($key,24*60*60,time());
            return DB::table($this->table_chat_private_log)->insertGetId([
                'room_id' => $room_id,
                'user_id' => $user_id,
                'to_user_id' => $to_user_id,
                'date' =>date('Y-m-d')
            ]);
        }
    }

    /**进厅记录
     * @param $room_id
     * @param $user_id
     * @param $isSearch  是否是通过搜索进来的用户
     * @return int
     */
    public function insertJoinLog($room_id ,$user_id, $isSearch){
        //只有是用户搜索后进入房间才记录
        if ($isSearch == 1) {
            DB::table('room_search_join_log')->insertGetId([
                'room_id' => $room_id,
                'user_id' => $user_id,
                'date' =>date('Y-m-d'),
            ]);
        }

        $key = "ROOM:".date('Ymd').":".$room_id.":".$user_id;
        $data = Redis::get($key);
        if(empty($data)) {
            Redis::setex($key, 24 * 60 * 60, time());
            try {
                DB::table($this->table_join_log)->insertGetId([
                    'room_id' => $room_id,
                    'user_id' => $user_id,
                    'date' => date('Y-m-d'),
                ]);
            }catch (\Exception $exception){

            }
        }
    }

    /**分享记录
     * @param $room_id
     * @param $user_id
     * @return int
     */
    public function addShare($room_id ,$user_id){
        return DB::table('room_share')->insertGetId([
            'room_id' => $room_id,
            'user_id' => $user_id,
            'date' =>date('Y-m-d')
        ]);
    }

    /**获取后台配置的推荐房间
     * @return array
     */
    public function getRecoRecommend(){
        $res = Redis::HGETALL($this->redis_room_reco_recommend);
        return $res ?? [];
    }

    public function getReco2Recommend(){
        $reco = Redis::HGETALL($this->redis_room_reco2_recommend);
        $data = [];
        if(!empty($reco)){
            foreach ($reco as $k=>$r){
                $label_sort = explode('_' ,$r);
                $temp['room_id'] = $k;
                $temp['sort'] = $label_sort[1];
                $data[] = $temp;
            }
            $sort = array_column($data, 'sort');
            array_multisort($sort, SORT_DESC, $data);
            $data = array_column($data ,null ,'room_id');
        }
        return $data;
    }

    /**获取后台配置的推荐房间
     * @return array
     */
    public function getRoomRecommend(){
        $res = Redis::HGETALL($this->redis_room_reco2_recommend);
        $arr = [];
        if(count($res) > 0) {
            $i = 0;
            foreach ($res as $k => $v) {
                $temp = explode('_' ,$v);
                if(!empty($temp)){
                    $arr[$i]['id'] = (int)$temp[0];
                    $arr[$i]['label_id'] = (int)$temp[0];
                    $roomInfo = DB::table($this->table)->select('room_uid', 'name')->where('room_id', '=', $k)->first();
                    $roomInfo = $this->objToArray($roomInfo);
                    $arr[$i]['room_uid'] = $roomInfo['room_uid'] ?? '';
                    $arr[$i]['room_name'] = $roomInfo['name'] ?? '';
                    $arr[$i]['room_id'] = $k;
                    $arr[$i]['sort'] = $temp[1];
                    $arr[$i]['label_res'] = Redis::HGET($this->redis_room_label ,$k) ?? '';
                    $i++;
                }

            }
        }
        return $res ? $arr : [];
    }

    /**
     * 设置房间推荐标签
     */
    public function setRoomRecommend($input ,$is_recommend = true)
    {
       if(!empty($input['label_id'])){
           $nowTime = date('Y-m-d H:i:s');
           $input['starttime'] = empty($input['starttime']) ? date('Y-m-d H:i:s') : $input['starttime'];
           $input['endtime'] = empty($input['endtime']) ? date('Y-m-d H:i:s' ,time()+3*24*60*60) : $input['endtime'];
           DB::INSERT("INSERT INTO zb_room_label (`room_id`,`label_id`,`updated_time`,`starttime`,`endtime`, `special_recommend_resource_url`, `special_recommend_start_time`, `special_recommend_end_time`) 
VALUE({$input['room_id']}, {$input['label_id']},'{$nowTime}' ,'{$input['starttime']}' ,'{$input['endtime']}', '{$input['special_recommend_resource_url']}', '{$input['special_recommend_start_time']}', '{$input['special_recommend_end_time']}') 
ON DUPLICATE KEY UPDATE label_id={$input['label_id']},starttime = '{$input['starttime']}' ,
    endtime = '{$input['endtime']}' ,updated_time = '{$nowTime}', special_recommend_resource_url = '{$input['special_recommend_resource_url']}', 
    special_recommend_start_time = '{$input['special_recommend_start_time']}', special_recommend_end_time='{$input['special_recommend_end_time']}'");
       }
        if($is_recommend){
            $redis = $this->redis_room_reco2_recommend;
            Redis::hset($redis, $input['room_id'], $input['label_id'].'_'.$input['sort']);
        }
    }

    /**删除房间推荐
     * @param $room_id
     */
    public function removeRoomRecommend($room_id)
    {
        $redis = $this->redis_room_reco2_recommend;
        Redis::hdel($redis, $room_id);
    }

    /**删除房间标签
     * @param $room_id
     * @return int
     */
    public function delRoomLabel($room_id){
        Redis::hdel($this->redis_room_label ,$room_id);
        $this->delCache($room_id);
        return DB::table('room_label')->where('room_id' ,$room_id)->delete();
    }

    /**获取游戏房间
     * @return array|mixed
     */
    public function  getGameRoomInfo(){
        $res =DB::table($this->roomTypeTable)
            ->select('type_id' ,'type_name' ,'img_home_url' ,'img_room_url' ,'img_roomedit_url','img_room_fast_url','img_room_fast_url2')
            ->where('type_id','>=' ,'18')
            ->where('type_id' ,'<=' ,37)
            ->where('is_show' ,1)
            ->orderBy('sort' ,'asc')
            ->get();
        if(!empty($res)){
            $res = $this->objToArray($res);
            foreach ($res as &$v){
                if (!empty($v['img_home_url'])){
                    $v['img_home_url'] =  build_image($v['img_home_url']);
                }
                if (!empty($v['img_room_url'])){
                    $v['img_room_url'] =  build_image($v['img_room_url']);
                }
                if (!empty($v['img_roomedit_url'])){
                    $v['img_roomedit_url'] =  build_image($v['img_roomedit_url']);
                }
                if (!empty($v['img_cbd_url'])){
                    $v['img_cbd_url'] =  build_image($v['img_cbd_url']);
                }
                if (!empty($v['img_room_fast_url'])){
                    $v['img_room_fast_url'] =  build_image($v['img_room_fast_url']);
                }
                if (!empty($v['img_room_fast_url2'])){
                    $v['img_room_fast_url2'] =  build_image($v['img_room_fast_url2']);
                }
            }
            return  $res;
        }
        return [];
    }

    /**
     * 定时设置/取消设置 房间标签
     */
    public function handleRoomLabel(){
        $all = DB::table('room_label')->get();
        $all = $this->objToArray($all);
        $labelData = DB::table($this->table_recommend_label)->select('id','animate_resource')->get();
        $labelData = $this->objToArray($labelData);
        $labelData = array_column($labelData ,null ,'id');
        foreach ($all as $a){
            $room_id = $a['room_id'];
            $is_have = Redis::HGET($this->redis_room_label ,$room_id);
            $currentTime = date('Y-m-d H:i:s');
            if(isset($labelData[$a['label_id']])){
                if($currentTime > $a['starttime'] && $currentTime < $a['endtime']){
                    Redis::hset($this->redis_room_label ,$room_id ,build_image($labelData[$a['label_id']]['animate_resource']));
                    $this->delCache($room_id);
                }
            }

            if($a['special_recommend_start_time'] && $currentTime > $a['special_recommend_start_time']
                && $a['special_recommend_end_time'] && $currentTime < $a['special_recommend_end_time']
                && $a['special_recommend_resource_url']){
                Redis::hset($this->redis_room_label ,$room_id ,getFullImageUrl($a['special_recommend_resource_url']));
                $this->delCache($room_id);
            }

            if($is_have){
                $del = false;
                if ($a['special_recommend_end_time']) {
                    if ($currentTime > $a['endtime'] && $currentTime > $a['special_recommend_end_time']) {
                        $del = true;
                    }
                } else {
                    if ($currentTime > $a['endtime']) {
                        $del = true;
                    }
                }

                if ($del === true) {
                    Redis::hdel($this->redis_room_label ,$room_id);
                    $this->delCache($room_id);
                    DB::table('room_label')->where('room_id' ,$room_id)->delete();
                }
            }
        }
    }

    /**添加一条邀请记录
     * @param $room_id
     * @param $user_id
     * @param $invite_user_id
     * @return bool
     */
    public function add_admin_invite($room_id, $user_id,$invite_user_id){
        $data = [
            'room_id'=>$room_id,
            'user_id'=>$user_id,
            'invite_user_id'=>$invite_user_id,
            'role_id' =>1 ,
        ];
        return DB::table($this->roleInviteTable)->insert($data);
    }

    /**获取房间管理邀请记录
     * @param $room_id
     * @param $invite_user_id
     * @return mixed
     */
    public function get_admin_invite_log($room_id,$invite_user_id){
        $res = DB::table($this->roleInviteTable)
            ->where(['room_id'=>$room_id , 'invite_user_id'=>$invite_user_id])
            ->first();
        return $this->objToArray($res);
    }
    /**获取动态背景资源
     * @param $id
     * @return mixed
     */
    public function get_dynamic($id){
        $res = DB::table('room_dynamic')
            ->where('id' ,$id)
            ->first();
        return $this->objToArray($res);
    }

    /**删除邀请记录
     * @param $room_id
     * @param $invite_user_id
     * @return int
     */
    public function del_admin_invite_log($room_id ,$invite_user_id){
        return DB::table($this->roleInviteTable)
            ->where(['room_id'=>$room_id , 'invite_user_id'=>$invite_user_id])
            ->delete();
    }

    /**获取有效的邀请记录
     * @param $room_id
     * @return mixed
     */
    public function get_admin_valid_invite($room_id){
        $res = DB::table($this->roleInviteTable)
            ->where('room_id' ,$room_id)
            ->where('created_at','>',date('Y-m-d H:i:s' ,strtotime('-1 days')))
            ->get();
        return $this->objToArray($res);
    }

    /**设置开播消息 10分钟内有效
     * @param $room_id
     */
    public function setBroadcastMsg($room_id){
        Redis::SETEX('ROOM:BROADCAST:MSG:'.$room_id ,10*60 ,time());
    }

    /**获取开播消息记录
     * @param $room_id
     * @return int
     */
    public function getBroadcastMsg($room_id){
        return Redis::get('ROOM:BROADCAST:MSG:'.$room_id) ?? 0;
    }
    /**设置动态背景
     * @param $room_id
     * @param $source
     * @param $time
     */
    public function setDynamic($room_id ,$source ,$time){
        Redis::setex($this->redis_dynamic_cover.$room_id ,$time ,$source);
        $this->delCache($room_id);
    }

    public function getRoomLableByRoomIds(array $idArr = []): array {
        if(empty($idArr)) return [];
        $res = Db::table('room_label AS rl')
        ->leftJoin('room_recommend_label AS rrl', 'rl.label_id', '=', 'rrl.id')
        ->whereIn('rl.room_id', $idArr)
        ->get(['rl.room_id', 'rl.label_id', 'rl.starttime', 'rl.endtime', 'rl.special_recommend_resource_url', 'rl.special_recommend_start_time',
            'rl.special_recommend_end_time','rrl.id', 'rrl.animate_resource', 'rrl.new_animate_resource'])
        ->toArray();
        $res = $this->objToArray($res);
        $picDomain = getPicDomain();
        foreach($res as &$item) {

            //验证标签是否过期
            $sTime = empty($item['starttime']) ? 0 : strtotime($item['starttime']);
            $eTime = empty($item['endtime']) ? 0 : strtotime($item['endtime']);

            if ($sTime > 0 && $eTime > 0 && ($sTime > time() || $eTime < time())) {
                $item['animate_resource'] = '';
                $item['new_animate_resource'] = '';
            }else{
                $item['animate_resource'] = $item['animate_resource'] ? $picDomain. $item['animate_resource'] : '';
                $item['new_animate_resource'] = $item['new_animate_resource'] ? $picDomain. $item['new_animate_resource'] : '';
            }

            $item['special_animate_resource'] = '';//特殊推荐标签
            if ($item['special_recommend_resource_url'] && $item['special_recommend_start_time'] && $item['special_recommend_end_time']) {
                $startTime = strtotime($item['special_recommend_start_time']);
                $endTime = strtotime($item['special_recommend_end_time']);
                if ($startTime <= time() && $endTime > time()) {
                    $item['special_animate_resource'] = getFullImageUrl($item['special_recommend_resource_url']);
                }
            }
        }
        unset($item);
        return $res;
    }

    /**
     * 创建直播计划
     */
    public function createRoomLivePlan(array $data = []): int {
        return DB::table($this->roomLivePlanTable)->insertGetId([
            'platform_id' => $data['platform_id'] ?? 0,
            'host_id' => $data['host_id'] ?? 0,
            'price' => $data['price'] ?? 0,
            'start_time' => $data['start_time'] ?? 0,
            'end_time' => $data['end_time'] ?? 0,
            'room_id' => $data['room_id'] ?? 0,
            'follow_id' => $data['follow_id'] ?? 0,
            'remark' => $data['remark'] ?? '',
            'host_name' => $data['host_name'] ?? '',
            'type' => $data['type'] ?? 0,
            'follow_name' => $data['follow_name'] ?? ''
        ]);
    }

    /**
     * 更新直播计划
     */
    public function updateRoomLivePlan(int $id = 0, array $data = []):int {
        return DB::table($this->roomLivePlanTable)->where('id', $id)->update($data);
    }

    public function deleteRoomLivePlan(int $id = 0):int {
        return DB::table($this->roomLivePlanTable)->delete($id);
    }

    /**
     * 根据房间id批量获取最新的直播计划
     */
    public function getRoomLivePlanByRoomIds(string $roomIds = '') {
        $nowTime = time();
        $sql = "select max(id) id from `zb_room_live_plan` where room_id in (%s) and start_time<=%s and end_time>=%s group by room_id";

        $sql = sprintf($sql, $roomIds, $nowTime, $nowTime);
        $res = DB::select($sql);
        $res = $this->objToArray($res);
        if(!$res) return [];

        $planIdArr = array_column($res, 'id');
        $res = DB::table($this->roomLivePlanTable)->whereIn('id', $planIdArr)
        ->get();
        return $this->objToArray($res);
    }

    /**
     * 根据房间id获取最新的直播计划
     */
    public function getNewRoomLivePlanByRoomId(int $roomId):array {
        $nowTime = time();
        $sql = "select max(id) id, `start_time`,`end_time`,`type` from `zb_room_live_plan` where room_id=%s and start_time<=%s and end_time>=%s limit 1";
        $sql = sprintf($sql, $roomId, $nowTime, $nowTime);
        $res = DB::select($sql);
        return $this->objToArray($res);
    }

    /**
     * 批量插入搜索记录
     */
    public function batchInsertRoomLiveSearchRecords(array $data = []): int {
        return DB::table($this->roomLiveSearchRecords)->insert($data);
    }

    /**
     * 保存有效的直播用户
     */
    public function insertRoomLivePlanActive(array $data = []): int {
        return DB::table($this->roomLivePlanActive)->insertGetId($data);
    }

    /**
     * 判断用户是否是该场直播的有效用户
     */
    public function effectiveSearchUser(int $planId, int $userId):array {
        $sql = "select max(id) id from `zb_room_live_search_records` where plan_id=%s and join_user_id=%s limit 1";
        $sql = sprintf($sql, $planId, $userId);
        $res = DB::select($sql);
        $res = $this->objToArray($res);
        if(!$res || !is_numeric($res['0']['id'])) return [];
        $res = DB::table($this->roomLiveSearchRecords)->where('id', $res[0]['id'])->first();
        return $this->objToArray($res);
    }

    public function removeRoomLivePlan(string $id = '') {
        return DB::table($this->roomLivePlanTable)->delete($id);
    }

    public function getRoomRecommendLabelById(int $id, array $fields = ['*']): array {
        $res = DB::table($this->table_recommend_label)->where('id', $id)->limit(1)->first($fields);
        $res = $this->objToArray($res);
        if(!$res) return [];
        $picDomain = getPicDomain();
        $res['new_animate_resource'] = $picDomain.$res['new_animate_resource'];
        $res['animate_resource'] = $picDomain.$res['animate_resource'];
        return $res;
    }

    /**
     * 设置神豪位开关
     */
    public function setGodHaoSwitch(int $roomId = 0, int $switch = 0): int {
        return (int) Redis::HSET($this->redis_room_god_hao_key, $roomId, $switch);
    }

    /**
     * 获取神豪位开关
     */
    public function getGodHaoSwitch(int $roomId = 0): int {
        return (int) Redis::HGET($this->redis_room_god_hao_key, $roomId);
    }

    /**
     * 获取已认证房间类型id
     * @return array
     */
    public function getCertifiedRoomTypeIds()
    {
        $roomTypes = DB::table("room_type")
            ->select(['type_id'])
            ->where('certified', '=', 1)
            ->orderBy('sort', 'DESC')->get();
        $result = self::objToArray($roomTypes);
        $data = [];
        foreach ($result as $v) {
            $data[] = $v['type_id'];
        }

        return $data;
    }

    public function addDynamic($img,$url,$name){
        return DB::table($this->roomDynamicTable)->insert(['img'=>$img,'url'=>$url,'name'=>$name,'created_at'=>time()]);
    }
    public function updateDynamic($id,$img,$url,$name){
        return DB::table($this->roomDynamicTable)->where('id',$id)->update(['img'=>$img,'url'=>$url,'name'=>$name]);
    }
    public function delDynamic($id){
        return DB::table($this->roomDynamicTable)->delete($id);
    }

    /**
     * @desc 从缓存获取房间类型列表
     * @author zxiaofee
     * @param int $certified -1 全(部默认值) 0 非认证 1 认证房间
     * @return string
     */
    public function get_room_types_from_cache($certified = -1){
        return Redis::get($this->redis_room_type_list_key . $certified);
    }

    /**
     * @desc 缓存房间泪飙
     * @author zxiaofee
     * @param string $room_types 需要缓存的房间类型列表json字符串
     * @param int $certified -1 全(部默认值) 0 非认证 1 认证房间
     * @return bool
     */
    public function set_room_types_to_cache($room_types, $certified = -1){
        return Redis::setex($this->redis_room_type_list_key . $certified, 10*60 ,$room_types);
    }

    public function getRoomTypeByRoomId($roomId){
        $result = DB::table($this->table)
            ->select(['room_type', 'business_type'])
            ->where('room_id', '=', $roomId)
            ->first();
        return $this->objToArray($result);
    }


    /**
     * 根据房间ID&房间功能 获取开关状态
     *
     * @param int $roomId
     * @return array
     */
    public function getRoomBySwitch($roomId, $switch_key)
    {
        $result = DB::table($this->tableRoomSwitch)
            ->select(['room_id', 'switch_key', 'switch_value'])
            ->where('room_id', '=', $roomId)
            ->where('switch_key', '=', $switch_key)
            ->first();

        return self::objToArray($result);
    }

    /**
     * 添加开关
     * @param $roomId
     * @param $switch_key
     * @param $switch_value
     * @return bool
     */
    public function addRoomBySwitch($roomId, $switch_key, $switch_value){
        return DB::table($this->tableRoomSwitch)
            ->insert(
                [
                    'room_id'=>$roomId,
                    'switch_key'=> (string)$switch_key,
                    'switch_value'=>$switch_value,
                    'edit_time'=>time(),
                ]
            );
    }

    /**
     * 根据房间ID&房间功能 获取开关状态
     * @param $roomId
     * @param $switch_key
     * @param $switch_value
     */
    public function setRoomBySwitch($roomId, $switch_key, $switch_value)
    {
        return DB::table($this->tableRoomSwitch)
            ->where('room_id', $roomId)
            ->where('switch_key', $switch_key)
            ->update(['switch_value'=>$switch_value, 'edit_time'=>time()]);
    }


    public function addRoomAdmin($roomId,$adminName){
        return DB::table($this->roomAdmin)
            ->updateOrInsert(['room_id' => $roomId,], [
                'room_id' => $roomId,
                'admin_name' => $adminName,
            ]
        );
    }
    public function addMicroLog($room_id, $micro_id, $user_id,$type){
        try {
            DB::table($this->roomMicroLogTable)->insert([
                'user_id' => $user_id,
                'room_id' => $room_id,
                'micro_id' => $micro_id,
                'type'      => $type
            ]);
        }catch (\Exception $exception){
            write_log('RoomMicro','addMicroLog Error', [
                'user_id' => $user_id,
                'room_id' => $room_id,
                'micro_id' => $micro_id,
                'type'      => $type
            ]);
            write_log('RoomMicro','addMicroLog Error', $exception->getMessage() );
        }
    }

    /**
     * 设置已开启房间信息
     */
    public function setRoomOpenListCache($room_id, $field, $value){
        $chacheKey = $this->roomOpenListKey;
        $field = $room_id.':'.$field;
        Redis::HSET($chacheKey, $field, $value);
        Redis::EXPIRE($chacheKey, 3*86400);
    }

    /**
     * 自增已开启房间信息
     */
    public function IncrRoomOpenListCache($room_id, $field, $value){
        $chacheKey = $this->roomOpenListKey;
        $field = $room_id.':'.$field;
        Redis::HINCRBY($chacheKey, $field, $value);
        Redis::EXPIRE($chacheKey, 3*86400);
    }

    /**
     * 删除已开启房间信息
     */
    public function delRoomOpenListCache($room_id){
        $chacheKey = $this->roomOpenListKey;
        $field = $room_id.':roomId';
        Redis::HDEL($chacheKey, $field);
        $field = $room_id.':roomMode';
        Redis::HDEL($chacheKey, $field);
        $field = $room_id.':roomUserNum';
        Redis::HDEL($chacheKey, $field);
        $field = $room_id.':gameId';
        Redis::HDEL($chacheKey, $field);
        $field = $room_id.':pkId';
        Redis::HDEL($chacheKey, $field);
        $field = $room_id.':pkEndTime';
        Redis::HDEL($chacheKey, $field);
        $field = $room_id.':roomOpenId';
        Redis::HDEL($chacheKey, $field);
        Redis::EXPIRE($chacheKey, 3*86400);
    }

    /**
     * 获取已开启房间信息
     */
    public function getRoomOpenList($room_id, $field){
        $chacheKey = $this->roomOpenListKey;
        $field = $room_id.':'.$field;
        $value = Redis::HGET($chacheKey, $field);
        Redis::EXPIRE($chacheKey, 3*86400);

        return $value;
    }

    /**
     * 获取所有已开启房间信息
     */
    public function getAllRoomOpenList(){
        $chacheKey = $this->roomOpenListKey;
        $list = Redis::HGETALL($chacheKey);
        return $list;
    }
    /**
     * 插入或修改房间特殊封面配置
     * @return bool
     */
    public function InsertOrUpSpecailImg($data=[])
    {
        $checkinfo = DB::table($this->room_special_table)->where('roomid',$data['roomid'])->exists();
        $roomid = $data['roomid'];
        if (!empty($checkinfo))
        {
            $updata = $data;
            $status = DB::table($this->room_special_table)->where('roomid',$roomid)->update($updata);
        }else{
            $status = DB::table($this->room_special_table)->insert($data);
        }
        if ($status)
        {
            //计算开始时间和结束时间的时间差
            $diffdays = Carbon::parse($data['start_time'])->diffInDays($data['end_time'],true);
            Redis::SET($this->redis_room_cover_special.$roomid, $data['special_img'],'EX', $diffdays*86400);
        }
        return $status;
    }

    /**
     * 删除配置
     */
    public function delSpecailImg($roomid=0)
    {
        $status = DB::table($this->room_special_table)->where('roomid',$roomid)->delete();
        Redis::del($this->redis_room_cover_special.$roomid);
        return $status;
    }

    //记录房间开启日志
    public function insertRoomOpenLog($roomId, $userId){
        return DB::table($this->room_open_log_table)->insertGetId([
            'room_id' => $roomId,
            'user_id' => $userId,
        ]);
    }

    /**
     * 累加房间开启日志
     */
    public function incrRoomOpenLog($id, $field, $num)
    {
        if(empty($id)) {
            return false;
        }
        if($num < 1) {
            return false;
        }
        $res = DB::table($this->room_open_log_table)->where('id', $id)->increment($field, $num);

        return $res;
    }

    /**
     * 更新房间开启日志
     */
    public function updateRoomOpenLog($id, $upData)
    {
        if(empty($id) || empty($upData)) {
            return false;
        }

        $res = DB::table($this->room_open_log_table)->where('id', $id)->update($upData);

        return $res;
    }

    /**
     * 更新房间日志-来源热度卡
     */
    public function updateRoomOpenLogByhotCard($id, $hotNum)
    {
        if(empty($id) || empty($hotNum)) {
            return false;
        }

        $res = DB::table($this->room_open_log_table)->where('id', $id)->increment('hot_num',$hotNum);

        return $res;
    }

    /**
     * 新增房间用户聊天条数记录
     */
    public function createRoomUserMsg($data)
    {
        if(empty($data)) {
            return false;
        }
        $res = DB::table($this->room_user_msg_table)->insertGetId($data);

        return $res;
    }

    /**
     * 累加房间用户聊天条数记录
     */
    public function incrRoomUserMsg($id, $field, $num)
    {
        if(empty($id)) {
            return false;
        }
        if($num < 1) {
            return false;
        }
        $res = DB::table($this->room_user_msg_table)->where('id', $id)->increment($field, $num);

        return $res;
    }

    /**
     * 根据用户ID房间开启ID获取房间用户聊天条数记录
     */
    public function getRoomUserMsgByUserRoomOpen($roomOpenId, $userId)
    {
        $result = DB::table($this->room_user_msg_table)
            ->where('room_open_id', $roomOpenId)
            ->where('user_id', $userId)
            ->first();
        if(empty($result)) {
            return [];
        }

        return self::objToArray($result);
    }

    /**
     * 根据房间开启ID汇总房间用户聊天条数记录
     */
    public function getSumRoomUserMsgByRoomOpen($roomOpenId)
    {
        $result = DB::table($this->room_user_msg_table)
            ->selectRaw('sum(sms_num_1) as sms_num_1, sum(sms_num_2) as sms_num_2')
            ->where('room_open_id', $roomOpenId)
            ->first();
        if(empty($result)) {
            return [];
        }

        return self::objToArray($result);
    }

    /**
     * 获取房间开启日志
     */
    public function getRoomOpenLog($id)
    {
        $result = DB::table($this->room_open_log_table)
            ->where('id', $id)
            ->first();
        if(empty($result)) {
            return [];
        }

        return self::objToArray($result);
    }

    /**
     * 获取指定数量的大于指定时间房间开启日志
     */
    public function getRoomOpenLogByRoomIdLimitOpentime($roomId, $noId, $limit=7, $openTimeMin=3600)
    {
        $result = DB::table($this->room_open_log_table)
            ->where('room_id', $roomId)
            ->where('id', '<>', $noId)
            ->where('open_time_num', '>=', $openTimeMin)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();
        if(empty($result)) {
            return [];
        }

        return self::objToArray($result);
    }

    /**
     * 新增房间置顶配置
     */
    public function createRoomTop($data)
    {
        if(empty($data)) {
            return false;
        }
        if(isset($data['sort_num']) && $data['sort_num']<1) {
            $data['sort_num'] = 1;
        }
        if(isset($data['sort_num']) && $data['sort_num']>10000) {
            $data['sort_num'] = 10000;
        }
        $res = DB::table($this->room_top_table)->insertGetId($data);
        Redis::del($this->roomTopKey);

        return $res;
    }

    /**
     * 修改房间置顶配置
     */
    public function updateRoomTop($id, $upData, $where=[])
    {
        if(empty($id) || empty($upData)) {
            return false;
        }
        if(isset($upData['sort_num']) && $upData['sort_num']<1) {
            $upData['sort_num'] = 1;
        }
        if(isset($upData['sort_num']) && $upData['sort_num']>10000) {
            $upData['sort_num'] = 10000;
        }
        $query = DB::table($this->room_top_table)->where('id', $id);
        if(!empty($where)) {
            if(isset($where['is_delete'])) {
                $query = $query->where('is_delete', $where['is_delete']);
            }
        }

        $res = $query->update($upData);
        Redis::del($this->roomTopKey);

        return $res;
    }

    /**
     * 获取房间置顶配置
     */
    public function getRoomTop($roomId)
    {
        $result = DB::table($this->room_top_table)
            ->where('room_id', $roomId)
            ->where('is_delete', 0)
            ->first();
        if(empty($result)) {
            return [];
        }

        return self::objToArray($result);
    }

    /**
     * 获取所有房间置顶配置
     */
    public function getRoomTopAll($time)
    {
        $key = $this->roomTopKey;
        $list = Redis::get($key);
        if(empty($list)){
            $list = DB::table($this->room_top_table)
                ->select('room_id', 'sort_num','time_st','time_ed')
                ->where('is_delete', 0)
                ->get()->toArray();
            $list = self::objToArray($list);
            Redis::setex($key, 86400, json_encode($list));
        }else{
            $list = json_decode($list, true);
        }

        //过滤
        $result = [];
        foreach($list as $val) {
            if($val['time_st']<=$time && $time<=$val['time_ed']) {
                $result[] = $val;
            }
        }

        return $result;
    }

    /**
     * 获取房间真爱榜开关状态
     */
    public function get_love_rank_status($room_id){
        $status = 1;
        if(Redis::HEXISTS($this->loveRankOpenStatusKey,$room_id)){
            $status = Redis::HGET($this->loveRankOpenStatusKey,$room_id);
        }
        return $status;
    }

    //删除房间绑定结算用户
    public function deleteRoomFinanceUserTable($roomId)
    {
        $res = DB::table($this->roomFinanceUserTable)->where('room_id', $roomId)->where('is_delete', 0)->update(['is_delete'=>1]);

        return $res;
    }

    //新增房间绑定结算用户
    public function addRoomFinanceUserTable($userId, $roomId, $adminId)
    {
        if(empty($userId) || empty($roomId)) {
            return 0;
        }
        $data = [];
        $data['user_id'] = $userId;
        $data['room_id'] = $roomId;
        $data['admin_id'] = $adminId;

        $id = DB::table($this->roomFinanceUserTable)->insertGetId($data);

        return $id;
    }

    //获取房间绑定实时结算用户
    public function getRoomFinanceUserTable($roomId)
    {
        $info = DB::table($this->roomFinanceUserTable)->where('room_id', $roomId)->where('is_delete', 0)->first();
        $info = objToArray($info);
        if(!empty($info['user_id'])) {
            return $info['user_id'];
        }

        return 0;
    }

    /**
     * 获取房间欢迎语配置
     */
    public function getRoomWelcomeWord($roomId){
        $key = $this->roomWelcomeWordKey.$roomId;
        $list = Redis::get($key);
        if(empty($list)){
            $list = DB::table($this->roomWelcomeWordTable)->select(['id', 'union_id', 'room_id', 'content'])->where('room_id', $roomId)->where('is_delete', 0)->where('audit_status', 2)->get();
            $list = self::objToArray($list);
            if(!empty($list)) {
                Redis::setex($key, 86400, json_encode($list));
            }
        }else{
            $list = json_decode($list, true);
        }

        return $list;
    }

    /**
     * 获取房间欢迎语数量
     */
    public function getRoomWelcomeWordNum($roomId){
        $num = DB::table($this->roomWelcomeWordTable)->where('room_id', $roomId)->where('is_delete', 0)->count();

        return $num;
    }

    //新增房间欢迎语
    public function addRoomWelcomeWord($param)
    {
        $data['union_id'] = $param['union_id'];
        $data['room_id'] = $param['room_id'];
        $data['content'] = $param['content'];
        $data['audit_status'] = 1;
        $id = DB::table($this->roomWelcomeWordTable)->insertGetId($data);

        return $id;
    }

    /**
     * 获取房间欢迎语配置根据ID
     */
    public function getRoomWelcomeWordById($id){
        $list = DB::table($this->roomWelcomeWordTable)
            ->where('id', $id)
            ->where('is_delete', 0)
            ->first();
        $list = self::objToArray($list);

        return $list;
    }

    //更新房间欢迎语配置
    public function editRoomWelcomeWord($ids, $roomId, $data=[])
    {
        $upData = [];
        if(isset($data['content'])) {
            $upData['content'] = (string) $data['content'];
        }
        if(isset($data['audit_status'])) {
            $upData['audit_status'] = $data['audit_status'];
        }
        if(isset($data['is_delete'])) {
            $upData['is_delete'] = $data['is_delete'];
        }
        if(!empty($upData)) {
            DB::table($this->roomWelcomeWordTable)
                ->whereIn('id', $ids)
                ->update($upData);
        }

        //删除缓存
        $key = $this->roomWelcomeWordKey.$roomId;
        Redis::del($key);

        return 1;
    }

    /**
     * 获取房间欢迎语配置所有
     */
    public function getRoomWelcomeWordAll($roomId){
        $list = DB::table($this->roomWelcomeWordTable)
            ->select(['id', 'union_id', 'room_id', 'content', 'audit_status', 'created_at', 'updated_at'])
            ->where('room_id', $roomId)
            ->where('is_delete', 0)
            ->get();
        $list = self::objToArray($list);

        return $list;
    }

    //新增拍拍房记录记录
    public function addRoomPaipaiLog($data)
    {
        $id = DB::table($this->roomPaipaiLogTable)->insertGetId($data);

        return $id;
    }

    //更新拍拍房记录记录
    public function editRoomPaipaiLog($id, $data=[])
    {
        if(empty($id)) {
            return false;
        }
        if(!empty($data['incr_second_num'])) {
            return DB::table($this->roomPaipaiLogTable)->where('id', $id)->increment('second_num', $data['incr_second_num']);
        }

        $upData = [];
        if(isset($data['end_time'])) {
            $upData['end_time'] = (string) $data['end_time'];
        }
        if(isset($data['rank_id'])) {
            $upData['rank_id'] = $data['rank_id'];
        }
        if(isset($data['day'])) {
            $upData['day'] = (string) $data['day'];
        }
        if(!empty($upData)) {
            DB::table($this->roomPaipaiLogTable)
                ->where('id', $id)
                ->update($upData);
        }

        return 1;
    }

    /**
     * 更改房间隐藏状态
     */
    public function chaneHideStatus($roomId, $status){
        $res = DB::table($this->table)->where('room_id',$roomId)->update(['is_hide'=>$status]);
        return $res;
    }
}
